repo stringclasses 1k values | file_url stringlengths 96 373 | file_path stringlengths 11 294 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 6 values | commit_sha stringclasses 1k values | retrieved_at stringdate 2026-01-04 14:45:56 2026-01-04 18:30:23 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/google/MinStack.java | company/google/MinStack.java | //Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
//push(x) -- Push element x onto stack.
//pop() -- Removes the element on top of the stack.
//top() -- Get the top element.
//getMin() -- Retrieve the minimum element in the stack.
/**
* Your MinStack object will be instantiated and called as such:
* MinStack obj = new MinStack();
* obj.push(x);
* obj.pop();
* int param_3 = obj.top();
* int param_4 = obj.getMin();
*/
class MinStack {
class Node {
int data;
int min;
Node next;
public Node(int data, int min) {
this.data = data;
this.min = min;
this.next = null;
}
}
Node head;
/** initialize your data structure here. */
public MinStack() {
}
public void push(int x) {
if(head == null) {
head = new Node(x, x);
} else {
Node newNode = new Node(x, Math.min(x, head.min));
newNode.next = head;
head = newNode;
}
}
public void pop() {
head = head.next;
}
public int top() {
return head.data;
}
public int getMin() {
return head.min;
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/google/SentenceScreenFitting.java | company/google/SentenceScreenFitting.java | // Given a rows x cols screen and a sentence represented by a list of non-empty words, find how many times the given sentence can be fitted on the screen.
// Note:
// A word cannot be split into two lines.
// The order of words in the sentence must remain unchanged.
// Two consecutive words in a line must be separated by a single space.
// Total words in the sentence won't exceed 100.
// Length of each word is greater than 0 and won't exceed 10.
// 1 ≤ rows, cols ≤ 20,000.
// Example 1:
// Input:
// rows = 2, cols = 8, sentence = ["hello", "world"]
// Output:
// 1
// Explanation:
// hello---
// world---
// The character '-' signifies an empty space on the screen.
// Example 2:
// Input:
// rows = 3, cols = 6, sentence = ["a", "bcd", "e"]
// Output:
// 2
// Explanation:
// a-bcd-
// e-a---
// bcd-e-
// The character '-' signifies an empty space on the screen.
// Example 3:
// Input:
// rows = 4, cols = 5, sentence = ["I", "had", "apple", "pie"]
// Output:
// 1
// Explanation:
// I-had
// apple
// pie-I
// had--
// The character '-' signifies an empty space on the screen.
public class SentenceScreenFitting {
public int wordsTyping(String[] sentence, int rows, int cols) {
String s = String.join(" ", sentence) + " ";
int start = 0;
int l = s.length();
for(int i = 0; i < rows; i++) {
start += cols;
if(s.charAt(start % l) == ' ') {
start++;
} else {
while(start > 0 && s.charAt((start - 1) % l) != ' ') {
start--;
}
}
}
return start / s.length();
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/google/GeneralizedAbbreviation.java | company/google/GeneralizedAbbreviation.java | // Write a function to generate the generalized abbreviations of a word.
// Example:
// Given word = "word", return the following list (order does not matter):
// ["word", "1ord", "w1rd", "wo1d", "wor1", "2rd", "w2d", "wo2", "1o1d", "1or1", "w1r1", "1o2", "2r1", "3d", "w3", "4"]
public class GeneralizedAbbreviation {
public List<String> generateAbbreviations(String word) {
List<String> result = new ArrayList<String>();
backtrack(result, word, 0, "", 0);
return result;
}
void backtrack(List result, String word, int position, String current, int count) {
if(position == word.length()) {
if(count > 0) {
current += count;
}
result.add(current);
} else {
backtrack(result, word, position + 1, current, count + 1);
backtrack(result, word, position + 1, current + (count > 0 ? count : "") + word.charAt(position), 0);
}
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/google/MaximumProductOfWordLengths.java | company/google/MaximumProductOfWordLengths.java | // Given a string array words, find the maximum value of length(word[i]) * length(word[j]) where the two words do not share common letters. You may assume that each word will contain only lower case letters. If no such two words exist, return 0.
// Example 1:
// Given ["abcw", "baz", "foo", "bar", "xtfn", "abcdef"]
// Return 16
// The two words can be "abcw", "xtfn".
// Example 2:
// Given ["a", "ab", "abc", "d", "cd", "bcd", "abcd"]
// Return 4
// The two words can be "ab", "cd".
// Example 3:
// Given ["a", "aa", "aaa", "aaaa"]
// Return 0
// No such pair of words.
public class MaximumProductOfWordLengths {
public int maxProduct(String[] words) {
if(words.length == 0 || words == null) {
return 0;
}
int length = words.length;
int[] value = new int[length];
int max = 0;
for(int i = 0; i < length; i++) {
String temp = words[i];
value[i] = 0;
for(int j = 0; j < temp.length(); j++) {
value[i] |= 1 << (temp.charAt(j) - 'a');
}
}
for(int i = 0; i < length; i++) {
for(int j = 1; j < length; j++) {
if((value[i] & value[j]) == 0 && (words[i].length() * words[j].length()) > max) {
max = words[i].length() * words[j].length();
}
}
}
return max;
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/google/SpiralMatrix.java | company/google/SpiralMatrix.java | //Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
//
//Example 1:
//
//Input:
//[
//[ 1, 2, 3 ],
//[ 4, 5, 6 ],
//[ 7, 8, 9 ]
//]
//Output: [1,2,3,6,9,8,7,4,5]
//Example 2:
//
//Input:
//[
//[1, 2, 3, 4],
//[5, 6, 7, 8],
//[9,10,11,12]
//]
//Output: [1,2,3,4,8,12,11,10,9,5,6,7]
class SpiralMatrix {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> result = new ArrayList<Integer>();
if(matrix == null || matrix.length == 0) {
return result;
}
int rowStart = 0;
int rowEnd = matrix.length - 1;
int colStart = 0;
int colEnd = matrix[0].length - 1;
while(rowStart <= rowEnd && colStart <= colEnd) {
for(int i = colStart; i <= colEnd; i++) {
result.add(matrix[rowStart][i]);
}
rowStart++;
for(int i = rowStart; i <= rowEnd; i++) {
result.add(matrix[i][colEnd]);
}
colEnd--;
if(rowStart <= rowEnd) {
for(int i = colEnd; i >= colStart; i--) {
result.add(matrix[rowEnd][i]);
}
}
rowEnd--;
if(colStart <= colEnd) {
for(int i = rowEnd; i >= rowStart; i--) {
result.add(matrix[i][colStart]);
}
}
colStart++;
}
return result;
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/google/InsertDeleteGetRandomO1.java | company/google/InsertDeleteGetRandomO1.java | //Design a data structure that supports all following operations in average O(1) time.
//insert(val): Inserts an item val to the set if not already present.
//remove(val): Removes an item val from the set if present.
//getRandom: Returns a random element from current set of elements. Each element must have the same probability of being returned.
//Example:
// Init an empty set.
//RandomizedSet randomSet = new RandomizedSet();
// Inserts 1 to the set. Returns true as 1 was inserted successfully.
//randomSet.insert(1);
// Returns false as 2 does not exist in the set.
//randomSet.remove(2);
// Inserts 2 to the set, returns true. Set now contains [1,2].
//randomSet.insert(2);
// getRandom should return either 1 or 2 randomly.
//randomSet.getRandom();
// Removes 1 from the set, returns true. Set now contains [2].
//randomSet.remove(1);
// 2 was already in the set, so return false.
//randomSet.insert(2);
// Since 2 is the only number in the set, getRandom always return 2.
//randomSet.getRandom();
class RandomizedSet {
HashMap<Integer, Integer> map;
ArrayList<Integer> values;
/** Initialize your data structure here. */
public RandomizedSet() {
map = new HashMap<Integer, Integer>();
values = new ArrayList<Integer>();
}
/** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
public boolean insert(int val) {
if(!map.containsKey(val)) {
map.put(val, val);
values.add(val);
return true;
}
else {
return false;
}
}
/** Removes a value from the set. Returns true if the set contained the specified element. */
public boolean remove(int val) {
if(map.containsKey(val)) {
map.remove(val);
values.remove(values.indexOf(val));
return true;
}
return false;
}
/** Get a random element from the set. */
public int getRandom() {
int random = (int)(Math.random() * values.size());
int valueToReturn = values.get(random);
return map.get(valueToReturn);
}
}
/**
* Your RandomizedSet object will be instantiated and called as such:
* RandomizedSet obj = new RandomizedSet();
* boolean param_1 = obj.insert(val);
* boolean param_2 = obj.remove(val);
* int param_3 = obj.getRandom();
*/
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/google/GuessNumberHigherOrLower.java | company/google/GuessNumberHigherOrLower.java | // We are playing the Guess Game. The game is as follows:
// I pick a number from 1 to n. You have to guess which number I picked.
// Every time you guess wrong, I'll tell you whether the number is higher or lower.
// You call a pre-defined API guess(int num) which returns 3 possible results (-1, 1, or 0):
// -1 : My number is lower
// 1 : My number is higher
// 0 : Congrats! You got it!
// Example:
// n = 10, I pick 6.
// Return 6.
/* The guess API is defined in the parent class GuessGame.
@param num, your guess
@return -1 if my number is lower, 1 if my number is higher, otherwise return 0
int guess(int num); */
public class GuessNumberHigherOrLower extends GuessGame {
public int guessNumber(int n) {
int left = 1;
int right = n;
while(left <= right) {
int mid = left + (right - left) / 2;
if(guess(mid) == 0) {
return mid;
} else if(guess(mid) > 0) {
left = mid + 1;
} else {
right = mid;
}
}
return -1;
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/google/GameOfLife.java | company/google/GameOfLife.java | // According to the Wikipedia's article: "The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970."
// Given a board with m by n cells, each cell has an initial state live (1) or dead (0). Each cell interacts with its eight neighbors (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article):
// Any live cell with fewer than two live neighbors dies, as if caused by under-population.
// Any live cell with two or three live neighbors lives on to the next generation.
// Any live cell with more than three live neighbors dies, as if by over-population..
// Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.
// Write a function to compute the next state (after one update) of the board given its current state.
// Follow up:
// Could you solve it in-place? Remember that the board needs to be updated at the same time: You cannot update some cells first and then use their updated values to update other cells.
// In this question, we represent the board using a 2D array. In principle, the board is infinite, which would cause problems when the active area encroaches the border of the array. How would you address these problems?
public class GameOfLife {
public void gameOfLife(int[][] board) {
if(board == null || board.length == 0) {
return;
}
int m = board.length;
int n = board[0].length;
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
int lives = liveNeighbors(board, m, n, i, j);
if(board[i][j] == 1 && lives >= 2 && lives <= 3) {
board[i][j] = 3;
}
if(board[i][j] == 0 && lives == 3) {
board[i][j] = 2;
}
}
}
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
board[i][j] >>= 1;
}
}
}
private int liveNeighbors(int[][] board, int m, int n, int i, int j) {
int lives = 0;
for(int x = Math.max(i - 1, 0); x <= Math.min(i + 1, m - 1); x++) {
for(int y = Math.max(j - 1, 0); y <= Math.min(j + 1, n - 1); y++) {
lives += board[x][y] & 1;
}
}
lives -= board[i][j] & 1;
return lives;
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/google/ValidParentheses.java | company/google/ValidParentheses.java | // Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
// The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.
public class ValidParentheses {
public boolean isValid(String s) {
if(s.length() % 2 == 1) {
return false;
}
Stack<Character> stack = new Stack<Character>();
for(int i = 0; i < s.length(); i++) {
if(s.charAt(i) == '(' || s.charAt(i) == '[' || s.charAt(i) == '{') {
stack.push(s.charAt(i));
} else if(s.charAt(i) == ')' && !stack.isEmpty() && stack.peek() == ')') {
stack.pop();
} else if(s.charAt(i) == ']' && !stack.isEmpty() && stack.peek() == ']') {
stack.pop();
} else if(s.charAt(i) == '}' && !stack.isEmpty() && stack.peek() == '}') {
stack.pop();
} else {
return false;
}
}
return stack.isEmpty();
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/google/BombEnemy.java | company/google/BombEnemy.java | // Given a 2D grid, each cell is either a wall 'W', an enemy 'E' or empty '0' (the number zero), return the maximum enemies you can kill using one bomb.
// The bomb kills all the enemies in the same row and column from the planted point until it hits the wall since the wall is too strong to be destroyed.
// Note that you can only put the bomb at an empty cell.
// Example:
// For the given grid
// 0 E 0 0
// E 0 W E
// 0 E 0 0
// return 3. (Placing a bomb at (1,1) kills 3 enemies)
public class BombEnemy {
public int maxKilledEnemies(char[][] grid) {
if(grid == null || grid.length == 0 || grid[0].length == 0) {
return 0;
}
int max = 0;
int row = 0;
int[] col = new int[grid[0].length];
for(int i = 0; i<grid.length; i++) {
for(int j = 0; j<grid[0].length;j++) {
if(grid[i][j] == 'W') {
continue;
}
if(j == 0 || grid[i][j-1] == 'W') {
row = killedEnemiesRow(grid, i, j);
}
if(i == 0 || grid[i-1][j] == 'W') {
col[j] = killedEnemiesCol(grid,i,j);
}
if(grid[i][j] == '0') {
max = (row + col[j] > max) ? row + col[j] : max;
}
}
}
return max;
}
//calculate killed enemies for row i from column j
private int killedEnemiesRow(char[][] grid, int i, int j) {
int num = 0;
while(j <= grid[0].length-1 && grid[i][j] != 'W') {
if(grid[i][j] == 'E') {
num++;
}
j++;
}
return num;
}
//calculate killed enemies for column j from row i
private int killedEnemiesCol(char[][] grid, int i, int j) {
int num = 0;
while(i <= grid.length -1 && grid[i][j] != 'W'){
if(grid[i][j] == 'E') {
num++;
}
i++;
}
return num;
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/google/WallsAndGates.java | company/google/WallsAndGates.java | // You are given a m x n 2D grid initialized with these three possible values.
// -1 - A wall or an obstacle.
// 0 - A gate.
// INF - Infinity means an empty room. We use the value 231 - 1 = 2147483647 to represent INF as you may assume that the distance to a gate is less than 2147483647.
// Fill each empty room with the distance to its nearest gate. If it is impossible to reach a gate, it should be filled with INF.
// For example, given the 2D grid:
// INF -1 0 INF
// INF INF INF -1
// INF -1 INF -1
// 0 -1 INF INF
// After running your function, the 2D grid should be:
// 3 -1 0 1
// 2 2 1 -1
// 1 -1 2 -1
// 0 -1 3 4
public class WallsAndGates {
public void wallsAndGates(int[][] rooms) {
//iterate through the matrix calling dfs on all indices that contain a zero
for(int i = 0; i < rooms.length; i++) {
for(int j = 0; j < rooms[0].length; j++) {
if(rooms[i][j] == 0) {
dfs(rooms, i, j, 0);
}
}
}
}
void dfs(int[][] rooms, int i, int j, int distance) {
//if you have gone out of the bounds of the array or you have run into a wall/obstacle, return
// room[i][j] < distance also ensure that we do not overwrite any previously determined distance if it is shorter than our current distance
if(i < 0 || i >= rooms.length || j < 0 || j >= rooms[0].length || rooms[i][j] < distance) {
return;
}
//set current index's distance to distance
rooms[i][j] = distance;
//recurse on all adjacent neighbors of rooms[i][j]
dfs(rooms, i + 1, j, distance + 1);
dfs(rooms, i - 1, j, distance + 1);
dfs(rooms, i, j + 1, distance + 1);
dfs(rooms, i, j - 1, distance + 1);
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/google/MissingRanges.java | company/google/MissingRanges.java | // Given a sorted integer array where the range of elements are in the inclusive range [lower, upper], return its missing ranges.
// For example, given [0, 1, 3, 50, 75], lower = 0 and upper = 99, return ["2", "4->49", "51->74", "76->99"].
public class MissingRanges {
public List<String> findMissingRanges(int[] nums, int lower, int upper) {
ArrayList<String> result = new ArrayList<String>();
for(int i = 0; i <= nums.length; i++) {
long start = i == 0 ? lower : (long)nums[i - 1] + 1;
long end = i == nums.length ? upper : (long)nums[i] - 1;
addMissing(result, start, end);
}
return result;
}
void addMissing(ArrayList<String> result, long start, long end) {
if(start > end) {
return;
} else if(start == end) {
result.add(start + "");
} else {
result.add(start + "->" + end);
}
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/google/PowerOfTwo.java | company/google/PowerOfTwo.java | //Given an integer, write a function to determine if it is a power of two.
//
//Example 1:
//
//Input: 1
//Output: true
//Example 2:
//
//Input: 16
//Output: true
//Example 3:
//
//Input: 218
//Output: false
class PowerOfTwo {
public boolean isPowerOfTwo(int n) {
long i = 1;
while(i < n) {
i <<= 1;
}
return i == n;
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/google/BinarySearchTreeIterator.java | company/google/BinarySearchTreeIterator.java | // Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.
// Calling next() will return the next smallest number in the BST.
// Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree.
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class BinarySearchTreeIterator {
Stack<TreeNode> stack;
public BSTIterator(TreeNode root) {
stack = new Stack<TreeNode>();
while(root != null) {
stack.push(root);
root = root.left;
}
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
return stack.isEmpty() ? false : true;
}
/** @return the next smallest number */
public int next() {
TreeNode nextSmallest = stack.pop();
TreeNode addToStack = nextSmallest.right;
while(addToStack != null) {
stack.add(addToStack);
addToStack = addToStack.left;
}
return nextSmallest.val;
}
}
/**
* Your BSTIterator will be called like this:
* BSTIterator i = new BSTIterator(root);
* while (i.hasNext()) v[f()] = i.next();
*/
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/google/MovingAverageFromDataStream.java | company/google/MovingAverageFromDataStream.java | // Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.
// For example,
// MovingAverage m = new MovingAverage(3);
// m.next(1) = 1
// m.next(10) = (1 + 10) / 2
// m.next(3) = (1 + 10 + 3) / 3
// m.next(5) = (10 + 3 + 5) / 3
/**
* Your MovingAverage object will be instantiated and called as such:
* MovingAverage obj = new MovingAverage(size);
* double param_1 = obj.next(val);
*/
public class MovingAverageFromDataStream {
double previousSum = 0.0;
int maxSize;
Queue<Integer> window;
/** Initialize your data structure here. */
public MovingAverage(int size) {
this.maxSize = size;
window = new LinkedList<Integer>();
}
public double next(int val) {
if(window.size() == maxSize) {
previousSum -= window.remove();
}
window.add(val);
previousSum += val;
return previousSum / window.size();
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/google/WiggleSort.java | company/google/WiggleSort.java | // Given an unsorted array nums, reorder it in-place such that nums[0] <= nums[1] >= nums[2] <= nums[3]....
// For example, given nums = [3, 5, 2, 1, 6, 4], one possible answer is [1, 6, 2, 5, 3, 4].
public class WiggleSort {
public void wiggleSort(int[] nums) {
for(int i = 1; i < nums.length; i++) {
int current = nums[i - 1];
if((i % 2 == 1) == (current > nums[i])) {
nums[i - 1] = nums[i];
nums[i] = current;
}
}
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/google/LongestSubstringWithAtMostKDistinctCharacters.java | company/google/LongestSubstringWithAtMostKDistinctCharacters.java | // Given a string, find the length of the longest substring T that contains at most k distinct characters.
// For example, Given s = “eceba” and k = 2,
// T is "ece" which its length is 3.
public class LongestSubstringWithAtMostKDistinctCharacters {
public int lengthOfLongestSubstringKDistinct(String s, int k) {
int[] count = new int[256]; // there are 256 ASCII characters in the world
int i = 0; // i will be behind j
int num = 0;
int res = 0;
for (int j = 0; j < s.length(); j++) {
if (count[s.charAt(j)] == 0) { // if count[s.charAt(j)] == 0, we know that it is a distinct character
num++;
}
count[s.charAt(j)]++;
while (num > k && i < s.length()) { // sliding window
count[s.charAt(i)]--;
if (count[s.charAt(i)] == 0){
num--;
}
i++;
}
res = Math.max(res, j - i + 1);
}
return res;
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/google/BullsAndCows.java | company/google/BullsAndCows.java | //You are playing the following Bulls and Cows game with your friend: You write down a number and ask your friend to guess what the number is. Each time your friend makes a guess, you provide a hint that indicates how many digits in said guess match your secret number exactly in both digit and position (called "bulls") and how many digits match the secret number but locate in the wrong position (called "cows"). Your friend will use successive guesses and hints to eventually derive the secret number.
//
//Write a function to return a hint according to the secret number and friend's guess, use A to indicate the bulls and B to indicate the cows.
//
//Please note that both secret number and friend's guess may contain duplicate digits.
//
//Example 1:
//
//Input: secret = "1807", guess = "7810"
//
//Output: "1A3B"
//
//Explanation: 1 bull and 3 cows. The bull is 8, the cows are 0, 1 and 7.
//Example 2:
//
//Input: secret = "1123", guess = "0111"
//
//Output: "1A1B"
//
//Explanation: The 1st 1 in friend's guess is a bull, the 2nd or 3rd 1 is a cow.
//Note: You may assume that the secret number and your friend's guess only contain digits, and their lengths are always equal.
class BullsAndCows {
public String getHint(String secret, String guess) {
int bulls = 0;
int cows = 0;
int[] counts = new int[10];
for(int i = 0; i < secret.length(); i++) {
if(secret.charAt(i) == guess.charAt(i)) {
bulls++;
} else {
if(counts[secret.charAt(i) - '0']++ < 0) {
cows++;
}
if(counts[guess.charAt(i) - '0']-- > 0) {
cows++;
}
}
}
return bulls + "A" + cows + "B";
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/google/BinaryTreePaths.java | company/google/BinaryTreePaths.java | // Given a binary tree, return all root-to-leaf paths.
// For example, given the following binary tree:
// 1
// / \
// 2 3
// \
// 5
// All root-to-leaf paths are:
// ["1->2->5", "1->3"]
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class BinaryTreePaths {
public List<String> binaryTreePaths(TreeNode root) {
List<String> result = new ArrayList<String>();
if(root == null) {
return result;
}
helper(new String(), root, result);
return result;
}
public void helper(String current, TreeNode root, List<String> result) {
if(root.left == null && root.right == null) {
result.add(current + root.val);
}
if(root.left != null) {
helper(current + root.val + "->", root.left, result);
}
if(root.right != null) {
helper(current + root.val + "->", root.right, result);
}
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/google/BinaryWatch.java | company/google/BinaryWatch.java | // A binary watch has 4 LEDs on the top which represent the hours (0-11), and the 6 LEDs on the bottom represent the minutes (0-59).
// Each LED represents a zero or one, with the least significant bit on the right.
// For example, the above binary watch reads "3:25".
// Given a non-negative integer n which represents the number of LEDs that are currently on, return all possible times the watch could represent.
// Example:
// Input: n = 1
// Return: ["1:00", "2:00", "4:00", "8:00", "0:01", "0:02", "0:04", "0:08", "0:16", "0:32"]
// Note:
// The order of output does not matter.
// The hour must not contain a leading zero, for example "01:00" is not valid, it should be "1:00".
// The minute must be consist of two digits and may contain a leading zero, for example "10:2" is not valid, it should be "10:02".
public class BinaryWatch {
public List<String> readBinaryWatch(int num) {
ArrayList<String> allTimes = new ArrayList<String>();
//iterate through all possible time combinations
for(int i = 0; i < 12; i++) {
for(int j = 0; j < 60; j++) {
//if the current number and n have the same number of bits the time is possible
if(Integer.bitCount(i * 64 + j) == num) {
//add the current time to all times arraylist
allTimes.add(String.format("%d:%02d", i, j));
}
}
}
return allTimes;
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/google/JudgeRouteCircle.java | company/google/JudgeRouteCircle.java | //Initially, there is a Robot at position (0, 0). Given a sequence of its moves, judge if this robot makes a circle, which means it moves back to the original place.
//
//The move sequence is represented by a string. And each move is represent by a character. The valid robot moves are R (Right), L (Left), U (Up) and D (down). The output should be true or false representing whether the robot makes a circle.
//
//Example 1:
//Input: "UD"
//Output: true
//Example 2:
//Input: "LL"
//Output: false
class JudgeRouteCircle {
public boolean judgeCircle(String moves) {
int UD = 0;
int LR = 0;
for(int i = 0; i < moves.length(); i++) {
if(moves.charAt(i) == 'U') {
UD++;
} else if(moves.charAt(i) == 'D') {
UD--;
} else if(moves.charAt(i) == 'L') {
LR++;
} else if(moves.charAt(i) == 'R') {
LR--;
}
}
return UD == 0 && LR == 0;
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/google/StrobogrammaticNumber.java | company/google/StrobogrammaticNumber.java | // A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down).
// Write a function to determine if a number is strobogrammatic. The number is represented as a string.
// For example, the numbers "69", "88", and "818" are all strobogrammatic.
public class StrobogrammaticNumber {
public boolean isStrobogrammatic(String num) {
for(int i = 0, j = num.length() - 1; i <= j; i++, j--) {
if(!"00 11 88 696".contains(num.charAt(i) + "" + num.charAt(j))) {
return false;
}
}
return true;
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/google/ReverseVowelsOfAString.java | company/google/ReverseVowelsOfAString.java | // Write a function that takes a string as input and reverse only the vowels of a string.
// Example 1:
// Given s = "hello", return "holle".
// Example 2:
// Given s = "leetcode", return "leotcede".
// Note:
// The vowels does not include the letter "y".
public class ReverseVowelsOfAString {
public String reverseVowels(String s) {
if(s == null || s.length() == 0) {
return s;
}
String vowels = "aeiouAEIOU";
char[] chars = s.toCharArray();
int start = 0;
int end = s.length() - 1;
while(start < end) {
while(start < end && !vowels.contains(chars[start] + "")) {
start++;
}
while(start < end && !vowels.contains(chars[end] + "")) {
end--;
}
char temp = chars[start];
chars[start] = chars[end];
chars[end] = temp;
start++;
end--;
}
return new String(chars);
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/google/WordBreak.java | company/google/WordBreak.java | // Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words. You may assume the dictionary does not contain duplicate words.
// For example, given
// s = "leetcode",
// dict = ["leet", "code"].
// Return true because "leetcode" can be segmented as "leet code".
public class WordBreak {
public boolean wordBreak(String s, Set<String> wordDict) {
boolean[] dp = new boolean[s.length() + 1];
dp[0] = true;
for(int i = 1; i <= s.length(); i++) {
for(int j = 0; j < i; j++) {
if(dp[j] && wordDict.contains(s.substring(j, i))) {
dp[i] = true;
break;
}
}
}
return dp[s.length()];
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/google/FindAllNumbersDisappearedInAnArray.java | company/google/FindAllNumbersDisappearedInAnArray.java | //Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
//
//Find all the elements of [1, n] inclusive that do not appear in this array.
//
//Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.
//
//Example:
//
//Input:
//[4,3,2,7,8,2,3,1]
//
//Output:
//[5,6]
class FindAllNumbersDisappearedInAnArray {
public List<Integer> findDisappearedNumbers(int[] nums) {
List<Integer> result = new ArrayList<Integer>();
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for(int i = 1; i <= nums.length; i++) {
map.put(i, 1);
}
for(int i = 0; i < nums.length; i++) {
if(map.containsKey(nums[i])) {
map.put(nums[i], -1);
}
}
for(int i: map.keySet()) {
if(map.get(i) != -1) {
result.add(i);
}
}
return result;
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/google/DecodeString.java | company/google/DecodeString.java | // Given an encoded string, return it's decoded string.
// The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer.
// You may assume that the input string is always valid; No extra white spaces, square brackets are well-formed, etc.
// Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there won't be input like 3a or 2[4].
public class DecodeString {
public String decodeString(String s) {
//declare empty string
String decoded = "";
//initialize stack to hold counts
Stack<Integer> countStack = new Stack<Integer>();
//initalize stack to hold decoded string
Stack<String> decodedStack = new Stack<String>();
//initialize index to zero
int index = 0;
//iterate through entire string
while(index < s.length()) {
//if the current character is numeric...
if(Character.isDigit(s.charAt(index))) {
int count = 0;
//determine the number
while(Character.isDigit(s.charAt(index))) {
count = 10 * count + (s.charAt(index) - '0');
index++;
}
//push the number onto the count stack
countStack.push(count);
} else if(s.charAt(index) == '[') {
//if the current character is an opening bracket
decodedStack.push(decoded);
decoded = "";
index++;
} else if(s.charAt(index) == ']') {
//if the current character is a closing bracket
StringBuilder temp = new StringBuilder(decodedStack.pop());
int repeatTimes = countStack.pop();
for(int i = 0; i < repeatTimes; i++) {
temp.append(decoded);
}
decoded = temp.toString();
index++;
} else {
//otherwise, append the current character to the decoded string
decoded += s.charAt(index);
index++;
}
}
//return the decoded string
return decoded;
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/google/InsertInterval.java | company/google/InsertInterval.java | // Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).
// You may assume that the intervals were initially sorted according to their start times.
// Example 1:
// Given intervals [1,3],[6,9], insert and merge [2,5] in as [1,5],[6,9].
// Example 2:
// Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] in as [1,2],[3,10],[12,16].
// This is because the new interval [4,9] overlaps with [3,5],[6,7],[8,10].
/**
* Definition for an interval.
* public class Interval {
* int start;
* int end;
* Interval() { start = 0; end = 0; }
* Interval(int s, int e) { start = s; end = e; }
* }
*/
public class InsertInterval {
public List<Interval> insert(List<Interval> intervals, Interval newInterval) {
int i = 0;
while(i < intervals.size() && intervals.get(i).end < newInterval.start) {
i++;
}
while(i < intervals.size() && intervals.get(i).start <= newInterval.end) {
newInterval = new Interval(Math.min(intervals.get(i).start, newInterval.start), Math.max(intervals.get(i).end, newInterval.end));
intervals.remove(i);
}
intervals.add(i, newInterval);
return intervals;
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/google/FlattenNestedListIterator.java | company/google/FlattenNestedListIterator.java | // Given a nested list of integers, implement an iterator to flatten it.
// Each element is either an integer, or a list -- whose elements may also be integers or other lists.
// Example 1:
// Given the list [[1,1],2,[1,1]],
// By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,1,2,1,1].
// Example 2:
// Given the list [1,[4,[6]]],
// By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,4,6].
/**
* // This is the interface that allows for creating nested lists.
* // You should not implement it, or speculate about its implementation
* public interface NestedInteger {
*
* // @return true if this NestedInteger holds a single integer, rather than a nested list.
* public boolean isInteger();
*
* // @return the single integer that this NestedInteger holds, if it holds a single integer
* // Return null if this NestedInteger holds a nested list
* public Integer getInteger();
*
* // @return the nested list that this NestedInteger holds, if it holds a nested list
* // Return null if this NestedInteger holds a single integer
* public List<NestedInteger> getList();
* }
*/
public class FlattenNestedListIterator implements Iterator<Integer> {
Stack<NestedInteger> stack = new Stack<NestedInteger>();
public NestedIterator(List<NestedInteger> nestedList) {
for(int i = nestedList.size() - 1; i >= 0; i--) {
stack.push(nestedList.get(i));
}
}
@Override
public Integer next() {
return stack.pop().getInteger();
}
@Override
public boolean hasNext() {
while(!stack.isEmpty()) {
NestedInteger current = stack.peek();
if(current.isInteger()) {
return true;
}
stack.pop();
for(int i = current.getList().size() - 1; i >= 0; i--) {
stack.push(current.getList().get(i));
}
}
return false;
}
}
/**
* Your NestedIterator object will be instantiated and called as such:
* NestedIterator i = new NestedIterator(nestedList);
* while (i.hasNext()) v[f()] = i.next();
*/
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/google/FindTheDifference.java | company/google/FindTheDifference.java | // Given two strings s and t which consist of only lowercase letters.
// String t is generated by random shuffling string s and then add one more letter at a random position.
// Find the letter that was added in t.
// Example:
// Input:
// s = "abcd"
// t = "abcde"
// Output:
// e
// Explanation:
// 'e' is the letter that was added.
public class FindTheDifference {
public char findTheDifference(String s, String t) {
int charCodeS = 0;
int charCodeT = 0;
for(int i = 0; i < s.length(); i++) {
charCodeS += (int)(s.charAt(i));
}
for(int i = 0; i < t.length(); i++) {
charCodeT += (int)(t.charAt(i));
}
return (char)(charCodeT - charCodeS);
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/google/ZigZagIterator.java | company/google/ZigZagIterator.java | // Given two 1d vectors, implement an iterator to return their elements alternately.
// For example, given two 1d vectors:
// v1 = [1, 2]
// v2 = [3, 4, 5, 6]
// By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1, 3, 2, 4, 5, 6].
// Follow up: What if you are given k 1d vectors? How well can your code be extended to such cases?
/**
* Your ZigzagIterator object will be instantiated and called as such:
* ZigzagIterator i = new ZigzagIterator(v1, v2);
* while (i.hasNext()) v[f()] = i.next();
*/
public class ZigZagIterator {
private Iterator<Integer> i;
private Iterator<Integer> j;
private Iterator<Integer> temp;
public ZigzagIterator(List<Integer> v1, List<Integer> v2) {
i = v1.iterator();
j = v2.iterator();
}
public int next() {
if(i.hasNext()) {
temp = i;
i = j;
j = temp;
}
return j.next();
}
public boolean hasNext() {
return i.hasNext() || j.hasNext();
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/google/TrappingRainWater.java | company/google/TrappingRainWater.java | // Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
// For example,
// Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.
public class TrappingRainWater {
public int trap(int[] height) {
int water = 0;
int leftIndex = 0;
int rightIndex = height.length - 1;
int leftMax = 0;
int rightMax = 0;
while(leftIndex <= rightIndex) {
leftMax = Math.max(leftMax, height[leftIndex]);
rightMax = Math.max(rightMax, height[rightIndex]);
if(leftMax < rightMax) {
water += leftMax - height[leftIndex];
leftIndex++;
} else {
water += rightMax - height[rightIndex];
rightIndex--;
}
}
return water;
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/google/CombinationSumIV.java | company/google/CombinationSumIV.java | // Given an integer array with all positive numbers and no duplicates, find the number of possible combinations that add up to a positive integer target.
// Example:
// nums = [1, 2, 3]
// target = 4
// The possible combination ways are:
// (1, 1, 1, 1)
// (1, 1, 2)
// (1, 2, 1)
// (1, 3)
// (2, 1, 1)
// (2, 2)
// (3, 1)
// Note that different sequences are counted as different combinations.
// Therefore the output is 7.
// Follow up:
// What if negative numbers are allowed in the given array?
// How does it change the problem?
// What limitation we need to add to the question to allow negative numbers?
public class CombinationSumIV {
public int combinationSum4(int[] nums, int target) {
int[] dp = new int[target + 1];
dp[0] = 1;
for(int i = 1; i < dp.length; i++) {
for(int j = 0; j < nums.length; j++) {
if(i - nums[j] >= 0) {
dp[i] += dp[i - nums[j]];
}
}
}
return dp[target];
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/google/LongestConsecutiveSequence.java | company/google/LongestConsecutiveSequence.java | // Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
// For example,
// Given [100, 4, 200, 1, 3, 2],
// The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.
// Your algorithm should run in O(n) complexity.
class LongestConsecutiveSequence {
public int longestConsecutive(int[] nums) {
if(nums == null || nums.length == 0) {
return 0;
}
Set<Integer> set = new HashSet<Integer>();
for(int n: nums) {
set.add(n);
}
int maxLength = 0;
for(int n: set) {
if(!set.contains(n - 1)) {
int current = n;
int currentMax = 1;
while(set.contains(n + 1)) {
currentMax++;
n++;
}
maxLength = Math.max(maxLength, currentMax);
}
}
return maxLength;
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/google/Utf8Validation.java | company/google/Utf8Validation.java | // A character in UTF8 can be from 1 to 4 bytes long, subjected to the following rules:
// For 1-byte character, the first bit is a 0, followed by its unicode code.
// For n-bytes character, the first n-bits are all one's, the n+1 bit is 0, followed by n-1 bytes with most significant 2 bits being 10.
// This is how the UTF-8 encoding would work:
// Char. number range | UTF-8 octet sequence
// (hexadecimal) | (binary)
// --------------------+---------------------------------------------
// 0000 0000-0000 007F | 0xxxxxxx
// 0000 0080-0000 07FF | 110xxxxx 10xxxxxx
// 0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx
// 0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
// Given an array of integers representing the data, return whether it is a valid utf-8 encoding.
// Note:
// The input is an array of integers. Only the least significant 8 bits of each integer is used to store the data. This means each integer represents only 1 byte of data.
// Example 1:
// data = [197, 130, 1], which represents the octet sequence: 11000101 10000010 00000001.
// Return true.
// It is a valid utf-8 encoding for a 2-bytes character followed by a 1-byte character.
// Example 2:
// data = [235, 140, 4], which represented the octet sequence: 11101011 10001100 00000100.
// Return false.
// The first 3 bits are all one's and the 4th bit is 0 means it is a 3-bytes character.
// The next byte is a continuation byte which starts with 10 and that's correct.
// But the second continuation byte does not start with 10, so it is invalid.
public class Utf8Validation {
public boolean validUtf8(int[] data) {
int count = 0;
for(int i : data) {
if(count == 0) {
if((i >> 5) == 0b110) {
count = 1;
} else if((i >> 4) == 0b1110) {
count = 2;
} else if((i >> 3) == 0b11110) {
count = 3;
} else if((i >> 7) == 0b1) {
return false;
}
} else {
if((i >> 6) != 0b10) {
return false;
}
count--;
}
}
return count == 0;
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/google/PowerOfXToTheN.java | company/google/PowerOfXToTheN.java | // Implement pow(x, n).
public class PowerOfXToTheN {
public double myPow(double x, int n) {
if(n == 0) {
return 1;
}
if(Double.isInfinite(x)) {
return 0;
}
if(n < 0) {
n = -n;
x = 1 / x;
}
return n % 2 == 0 ? myPow(x * x, n / 2) : x * myPow(x * x, n / 2);
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/google/SummaryRanges.java | company/google/SummaryRanges.java | // Given a sorted integer array without duplicates, return the summary of its ranges.
// For example, given [0,1,2,4,5,7], return ["0->2","4->5","7"].
public class SummaryRanges {
public List<String> summaryRanges(int[] nums) {
List<String> result = new ArrayList();
if(nums.length == 1) {
result.add(nums[0] + "");
return result;
}
for(int i = 0; i < nums.length; i++) {
int current = nums[i];
while(i + 1 < nums.length && (nums[i + 1] - nums[i] == 1)) {
i++;
}
if(current != nums[i]) {
result.add(current + "->" + nums[i]);
} else {
result.add(current + "");
}
}
return result;
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/snapchat/ReverseWordsInAString.java | company/snapchat/ReverseWordsInAString.java | //Given an input string, reverse the string word by word.
//For example,
//Given s = "the sky is blue",
//return "blue is sky the".
public class ReverseWordsInAString {
public String reverseWords(String s) {
String[] words = s.trim().split("\\s+");
String result = "";
for(int i = words.length - 1; i > 0; i--) {
result += words[i] + " ";
}
return result + words[0];
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/snapchat/MinStack.java | company/snapchat/MinStack.java | //Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
//push(x) -- Push element x onto stack.
//pop() -- Removes the element on top of the stack.
//top() -- Get the top element.
//getMin() -- Retrieve the minimum element in the stack.
/**
* Your MinStack object will be instantiated and called as such:
* MinStack obj = new MinStack();
* obj.push(x);
* obj.pop();
* int param_3 = obj.top();
* int param_4 = obj.getMin();
*/
class MinStack {
class Node {
int data;
int min;
Node next;
public Node(int data, int min) {
this.data = data;
this.min = min;
this.next = null;
}
}
Node head;
/** initialize your data structure here. */
public MinStack() {
}
public void push(int x) {
if(head == null) {
head = new Node(x, x);
} else {
Node newNode = new Node(x, Math.min(x, head.min));
newNode.next = head;
head = newNode;
}
}
public void pop() {
head = head.next;
}
public int top() {
return head.data;
}
public int getMin() {
return head.min;
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/snapchat/ValidSudoku.java | company/snapchat/ValidSudoku.java | //Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules. (http://sudoku.com.au/TheRules.aspx)
//The Sudoku board could be partially filled, where empty cells are filled with the character '.'.
//A partially filled sudoku which is valid.
//Note:
//A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.
class ValidSudoku {
public boolean isValidSudoku(char[][] board) {
for(int i = 0; i < board.length; i++){
HashSet<Character> rows = new HashSet<Character>();
HashSet<Character> columns = new HashSet<Character>();
HashSet<Character> box = new HashSet<Character>();
for (int j = 0; j < board[0].length; j++){
if(board[i][j] != '.' && !rows.add(board[i][j])) {
return false;
}
if(board[j][i]!='.' && !columns.add(board[j][i])) {
return false;
}
int rowIndex = (i / 3) * 3;
int columnIndex = (i % 3) * 3;
if(board[rowIndex + j / 3][columnIndex + j % 3] != '.' && !box.add(board[rowIndex + j / 3][columnIndex + j % 3])) {
return false;
}
}
}
return true;
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/yahoo/LinkedListCycle.java | company/yahoo/LinkedListCycle.java | //Given a linked list, determine if it has a cycle in it.
//Follow up:
//Can you solve it without using extra space?
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public boolean hasCycle(ListNode head) {
if(head == null || head.next == null) {
return false;
}
ListNode slow = head;
ListNode fast = head.next;
while(fast != null && fast.next != null && fast != slow) {
slow = slow.next;
fast = fast.next.next;
}
return fast == slow;
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/yahoo/ContainsDuplicate.java | company/yahoo/ContainsDuplicate.java | //Given an array of integers, find if the array contains any duplicates. Your function should return
//true if any value appears at least twice in the array, and it should return false if every element is distinct.
class ContainsDuplicate {
public boolean containsDuplicate(int[] nums) {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for(int i: nums) {
if(map.containsKey(i)) {
return true;
} else {
map.put(i, 1);
}
}
return false;
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/amazon/LinkedListCycle.java | company/amazon/LinkedListCycle.java | //Given a linked list, determine if it has a cycle in it.
//Follow up:
//Can you solve it without using extra space?
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public boolean hasCycle(ListNode head) {
if(head == null || head.next == null) {
return false;
}
ListNode slow = head;
ListNode fast = head.next;
while(fast != null && fast.next != null && fast != slow) {
slow = slow.next;
fast = fast.next.next;
}
return fast == slow;
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/amazon/KthLargestElementInAnArray.java | company/amazon/KthLargestElementInAnArray.java | // Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.
// For example,
// Given [3,2,1,5,6,4] and k = 2, return 5.
// Note:
// You may assume k is always valid, 1 ≤ k ≤ array's length.
public class KthLargestElementInAnArray {
public int findKthLargest(int[] nums, int k) {
int length = nums.length;
Arrays.sort(nums);
return nums[length - k];
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/amazon/NumberOfIslands.java | company/amazon/NumberOfIslands.java | // Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
// Example 1:
// 11110
// 11010
// 11000
// 00000
// Answer: 1
// Example 2:
// 11000
// 11000
// 00100
// 00011
// Answer: 3
public class NumberOfIslands {
char[][] gridCopy;
public int numIslands(char[][] grid) {
//set grid copy to the current grid
gridCopy = grid;
//initialize number of islands to zero
int numberOfIslands = 0;
//iterate through every index of the grid
for(int i = 0; i < grid.length; i++) {
for(int j = 0; j < grid[0].length; j++) {
//attempt to "sink" the current index of the grid
numberOfIslands += sink(gridCopy, i, j);
}
}
//return the total number of islands
return numberOfIslands;
}
int sink(char[][] grid, int i, int j) {
//check the bounds of i and j and if the current index is an island or not (1 or 0)
if(i < 0 || i >= grid.length || j < 0 || j >= grid[0].length || grid[i][j] == '0') {
return 0;
}
//set current index to 0
grid[i][j] = '0';
// sink all neighbors of current index
sink(grid, i + 1, j);
sink(grid, i - 1, j);
sink(grid, i, j + 1);
sink(grid, i, j - 1);
//increment number of islands
return 1;
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/amazon/ReverseLinkedList.java | company/amazon/ReverseLinkedList.java | // Reverse a singly linked list.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class ReverseLinkedList {
public ListNode reverseList(ListNode head) {
if(head == null) {
return head;
}
ListNode newHead = null;
while(head != null) {
ListNode next = head.next;
head.next = newHead;
newHead = head;
head = next;
}
return newHead;
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/amazon/MergeKSortedLists.java | company/amazon/MergeKSortedLists.java | // Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class MergeKSortedLists {
public ListNode mergeKLists(ListNode[] lists) {
if (lists==null||lists.length==0) {
return null;
}
PriorityQueue<ListNode> queue= new PriorityQueue<ListNode>(lists.length,new Comparator<ListNode>(){
@Override
public int compare(ListNode o1,ListNode o2){
if (o1.val<o2.val) {
return -1;
} else if (o1.val==o2.val) {
return 0;
} else {
return 1;
}
}
});
ListNode dummy = new ListNode(0);
ListNode tail=dummy;
for (ListNode node:lists) {
if (node!=null) {
queue.add(node);
}
}
while (!queue.isEmpty()){
tail.next=queue.poll();
tail=tail.next;
if (tail.next!=null) {
queue.add(tail.next);
}
}
return dummy.next;
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/amazon/EncodeAndDecodeTinyURL.java | company/amazon/EncodeAndDecodeTinyURL.java | //TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl
//and it returns a short URL such as http://tinyurl.com/4e9iAk.
//
//Design the encode and decode methods for the TinyURL service. There is no restriction on how your
//encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL
//and the tiny URL can be decoded to the original URL.
public class EncodeAndDecodeTinyURL {
HashMap<String, String> map = new HashMap<String, String>();
String characters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
int count = 1;
public String getKey() {
String key = "";
while(count > 0) {
count--;
key += characters.charAt(count);
count /= characters.length();
}
return key;
}
// Encodes a URL to a shortened URL.
public String encode(String longUrl) {
String key = getKey();
map.put(key, longUrl);
count++;
return "http://tinyurl.com/" + key;
}
// Decodes a shortened URL to its original URL.
public String decode(String shortUrl) {
return map.get(shortUrl.replace("http://tinyurl.com/", ""));
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.decode(codec.encode(url));
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/amazon/MinCostClimbingStairs.java | company/amazon/MinCostClimbingStairs.java | //On a staircase, the i-th step has some non-negative cost cost[i] assigned (0 indexed).
//
//Once you pay the cost, you can either climb one or two steps. You need to find minimum cost to reach the top of the floor, and you can either start from the step with index 0, or the step with index 1.
//
//Example 1:
//Input: cost = [10, 15, 20]
//Output: 15
//Explanation: Cheapest is start on cost[1], pay that cost and go to the top.
//Example 2:
//Input: cost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1]
//Output: 6
//Explanation: Cheapest is start on cost[0], and only step on 1s, skipping cost[3].
//Note:
//cost will have a length in the range [2, 1000].
//Every cost[i] will be an integer in the range [0, 999].
class MinCostClimbingStairs {
public int minCostClimbingStairs(int[] cost) {
if(cost == null || cost.length == 0) {
return 0;
}
if(cost.length == 1) {
return cost[0];
}
if(cost.length == 2) {
return Math.min(cost[0], cost[1]);
}
int[] dp = new int[cost.length];
dp[0] = cost[0];
dp[1] = cost[1];
for(int i = 2; i < cost.length; i++) {
dp[i] = Math.min(dp[i - 1] + cost[i], dp[i - 2] + cost[i]);
}
return Math.min(dp[cost.length - 1], dp[cost.length -2]);
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/amazon/TwoSum.java | company/amazon/TwoSum.java | // Given an array of integers, return indices of the two numbers such that they add up to a specific target.
// You may assume that each input would have exactly one solution, and you may not use the same element twice.
// Example:
// Given nums = [2, 7, 11, 15], target = 9,
// Because nums[0] + nums[1] = 2 + 7 = 9,
// return [0, 1].
public class TwoSum {
public int[] twoSum(int[] nums, int target) {
int[] result = new int[2];
HashMap<Integer, Integer> map = new HashMap<>();
for(int i = 0; i < nums.length; i++) {
if(map.containsKey(target - nums[i])) {
result[1] = i;
result[0] = map.get(target - nums[i]);
return result;
}
map.put(nums[i], i);
}
return result;
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/amazon/FirstUniqueCharacterInAString.java | company/amazon/FirstUniqueCharacterInAString.java | //Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.
//
//Examples:
//
//s = "leetcode"
//return 0.
//
//s = "loveleetcode",
//return 2.
//Note: You may assume the string contain only lowercase letters.
class FirstUniqueCharacterInAString {
public int firstUniqChar(String s) {
HashMap<Character, Integer> characters = new HashMap<Character, Integer>();
for(int i = 0; i < s.length(); i++) {
char current = s.charAt(i);
if(characters.containsKey(current)) {
characters.put(current, -1);
} else {
characters.put(current, i);
}
}
int min = Integer.MAX_VALUE;
for(char c: characters.keySet()) {
if(characters.get(c) > -1 && characters.get(c) < min) {
min = characters.get(c);
}
}
return min == Integer.MAX_VALUE ? -1 : min;
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/amazon/3Sum.java | company/amazon/3Sum.java | // Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
// Note: The solution set must not contain duplicate triplets.
// For example, given array S = [-1, 0, 1, 2, -1, -4],
// A solution set is:
// [
// [-1, 0, 1],
// [-1, -1, 2]
// ]
public class 3Sum {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
Arrays.sort(nums);
for(int i = 0; i < nums.length - 2; i++) {
if(i > 0 && nums[i] == nums[i - 1]) {
continue;
}
int j = i + 1;
int k = nums.length - 1;
int target = -nums[i];
while(j < k) {
if(nums[j] + nums[k] == target) {
ArrayList<Integer> temp = new ArrayList<Integer>();
temp.add(nums[i]);
temp.add(nums[j]);
temp.add(nums[k]);
result.add(temp);
j++;
k--;
while(j < k && nums[j] == nums[j - 1]) {
j++;
}
while(j < k && nums[k] == nums[k + 1]) {
k--;
}
} else if(nums[j] + nums[k] > target) {
k--;
} else {
j++;
}
}
}
return result;
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/amazon/AddTwoNumbers.java | company/amazon/AddTwoNumbers.java | // You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
// You may assume the two numbers do not contain any leading zero, except the number 0 itself.
// Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
// Output: 7 -> 0 -> 8
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class AddTwoNumbers {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode current1 = l1;
ListNode current2 = l2;
ListNode head = new ListNode(0);
ListNode currentHead = head;
int sum = 0;
while(current1 != null || current2 != null) {
sum /= 10;
if(current1 != null) {
sum += current1.val;
current1 = current1.next;
}
if(current2 != null) {
sum += current2.val;
current2 = current2.next;
}
currentHead.next = new ListNode(sum % 10);
currentHead = currentHead.next;
}
if(sum / 10 == 1) {
currentHead.next = new ListNode(1);
}
return head.next;
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/amazon/LetterCombinationsOfAPhoneNumber.java | company/amazon/LetterCombinationsOfAPhoneNumber.java | // Given a digit string, return all possible letter combinations that the number could represent.
// A mapping of digit to letters (just like on the telephone buttons) is given below.
// 2 - abc
// 3 - def
// 4 - ghi
// 5 - jkl
// 6 - mno
// 7 - pqrs
// 8 - tuv
// 9 - wxyz
// Input:Digit string "23"
// Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
class LetterCombinationsOfAPhoneNumber {
public List<String> letterCombinations(String digits) {
List<String> result = new ArrayList<String>();
if(digits == null || digits.length() == 0) {
return result;
}
String[] mapping = {
"0",
"1",
"abc",
"def",
"ghi",
"jkl",
"mno",
"pqrs",
"tuv",
"wxyz"
};
letterCombinationsRecursive(result, digits, "", 0, mapping);
return result;
}
public void letterCombinationsRecursive(List<String> result, String digits, String current, int index, String[] mapping) {
if(index == digits.length()) {
result.add(current);
return;
}
String letters = mapping[digits.charAt(index) - '0'];
for(int i = 0; i < letters.length(); i++) {
letterCombinationsRecursive(result, digits, current + letters.charAt(i), index + 1, mapping);
}
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/amazon/BestTimeToBuyAndSellStock.java | company/amazon/BestTimeToBuyAndSellStock.java | // Say you have an array for which the ith element is the price of a given stock on day i.
// If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
// Example 1:
// Input: [7, 1, 5, 3, 6, 4]
// Output: 5
// max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)
// Example 2:
// Input: [7, 6, 4, 3, 1]
// Output: 0
// In this case, no transaction is done, i.e. max profit = 0.
public class BestTimeToBuyAndSellStock {
public int maxProfit(int[] prices) {
//Kadane's algorithm
if(prices.length == 0) {
return 0;
}
int max = 0;
int min = prices[0];
for(int i = 1; i < prices.length; i++) {
if(prices[i] > min) {
max = Math.max(max, prices[i] - min);
} else {
min = prices[i];
}
}
return max;
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/amazon/MinStack.java | company/amazon/MinStack.java | //Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
//push(x) -- Push element x onto stack.
//pop() -- Removes the element on top of the stack.
//top() -- Get the top element.
//getMin() -- Retrieve the minimum element in the stack.
/**
* Your MinStack object will be instantiated and called as such:
* MinStack obj = new MinStack();
* obj.push(x);
* obj.pop();
* int param_3 = obj.top();
* int param_4 = obj.getMin();
*/
class MinStack {
class Node {
int data;
int min;
Node next;
public Node(int data, int min) {
this.data = data;
this.min = min;
this.next = null;
}
}
Node head;
/** initialize your data structure here. */
public MinStack() {
}
public void push(int x) {
if(head == null) {
head = new Node(x, x);
} else {
Node newNode = new Node(x, Math.min(x, head.min));
newNode.next = head;
head = newNode;
}
}
public void pop() {
head = head.next;
}
public int top() {
return head.data;
}
public int getMin() {
return head.min;
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/amazon/InsertDeleteGetRandomO1.java | company/amazon/InsertDeleteGetRandomO1.java | //Design a data structure that supports all following operations in average O(1) time.
//insert(val): Inserts an item val to the set if not already present.
//remove(val): Removes an item val from the set if present.
//getRandom: Returns a random element from current set of elements. Each element must have the same probability of being returned.
//Example:
// Init an empty set.
//RandomizedSet randomSet = new RandomizedSet();
// Inserts 1 to the set. Returns true as 1 was inserted successfully.
//randomSet.insert(1);
// Returns false as 2 does not exist in the set.
//randomSet.remove(2);
// Inserts 2 to the set, returns true. Set now contains [1,2].
//randomSet.insert(2);
// getRandom should return either 1 or 2 randomly.
//randomSet.getRandom();
// Removes 1 from the set, returns true. Set now contains [2].
//randomSet.remove(1);
// 2 was already in the set, so return false.
//randomSet.insert(2);
// Since 2 is the only number in the set, getRandom always return 2.
//randomSet.getRandom();
class RandomizedSet {
HashMap<Integer, Integer> map;
ArrayList<Integer> values;
/** Initialize your data structure here. */
public RandomizedSet() {
map = new HashMap<Integer, Integer>();
values = new ArrayList<Integer>();
}
/** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
public boolean insert(int val) {
if(!map.containsKey(val)) {
map.put(val, val);
values.add(val);
return true;
}
else {
return false;
}
}
/** Removes a value from the set. Returns true if the set contained the specified element. */
public boolean remove(int val) {
if(map.containsKey(val)) {
map.remove(val);
values.remove(values.indexOf(val));
return true;
}
return false;
}
/** Get a random element from the set. */
public int getRandom() {
int random = (int)(Math.random() * values.size());
int valueToReturn = values.get(random);
return map.get(valueToReturn);
}
}
/**
* Your RandomizedSet object will be instantiated and called as such:
* RandomizedSet obj = new RandomizedSet();
* boolean param_1 = obj.insert(val);
* boolean param_2 = obj.remove(val);
* int param_3 = obj.getRandom();
*/
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/amazon/ValidParentheses.java | company/amazon/ValidParentheses.java | // Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
// The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.
public class ValidParentheses {
public boolean isValid(String s) {
if(s.length() % 2 == 1) {
return false;
}
Stack<Character> stack = new Stack<Character>();
for(int i = 0; i < s.length(); i++) {
if(s.charAt(i) == '(' || s.charAt(i) == '[' || s.charAt(i) == '{') {
stack.push(s.charAt(i));
} else if(s.charAt(i) == ')' && !stack.isEmpty() && stack.peek() == ')') {
stack.pop();
} else if(s.charAt(i) == ']' && !stack.isEmpty() && stack.peek() == ']') {
stack.pop();
} else if(s.charAt(i) == '}' && !stack.isEmpty() && stack.peek() == '}') {
stack.pop();
} else {
return false;
}
}
return stack.isEmpty();
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/amazon/ProductOfArrayExceptSelf.java | company/amazon/ProductOfArrayExceptSelf.java | // Given an array of n integers where n > 1, nums, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].
// Solve it without division and in O(n).
// For example, given [1,2,3,4], return [24,12,8,6].
// Follow up:
// Could you solve it with constant space complexity? (Note: The output array does not count as extra space for the purpose of space complexity analysis.)
public class ProductOfArrayExceptSelf {
public int[] productExceptSelf(int[] nums) {
int n = nums.length;
int[] result = new int[n];
int left = 1;
for(int i = 0; i < nums.length; i++) {
if(i > 0) {
left *= nums[i - 1];
}
result[i] = left;
}
int right = 1;
for(int i = n - 1; i >= 0; i--) {
if(i < n - 1) {
right *= nums[i + 1];
}
result[i] *= right;
}
return result;
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/amazon/LongestPalindromicSubstring.java | company/amazon/LongestPalindromicSubstring.java | //Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
//Example:
//Input: "babad"
//Output: "bab"
//Note: "aba" is also a valid answer.
//Example:
//Input: "cbbd"
//Output: "bb"
class LongestPalindromicSubstring {
public String longestPalindrome(String s) {
if(s == null || s.length() == 0) {
return "";
}
String longestPalindromicSubstring = "";
for(int i = 0; i < s.length(); i++) {
for(int j = i + 1; j <= s.length(); j++) {
if(j - i > longestPalindromicSubstring.length() && isPalindrome(s.substring(i, j))) {
longestPalindromicSubstring = s.substring(i, j);
}
}
}
return longestPalindromicSubstring;
}
public boolean isPalindrome(String s) {
int i = 0;
int j = s.length() - 1;
while(i <= j) {
if(s.charAt(i++) != s.charAt(j--)) {
return false;
}
}
return true;
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/amazon/GroupAnagrams.java | company/amazon/GroupAnagrams.java | // Given an array of strings, group anagrams together.
// For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"],
// Return:
// [
// ["ate", "eat","tea"],
// ["nat","tan"],
// ["bat"]
// ]
// Note: All inputs will be in lower-case.
public class GroupAnagrams {
public List<List<String>> groupAnagrams(String[] strs) {
if(strs == null || strs.length == 0) {
return new ArrayList<List<String>>();
}
HashMap<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
Arrays.sort(strs);
for(String s : strs) {
char[] characters = s.toCharArray();
Arrays.sort(characters);
String key = String.valueOf(characters);
if(!map.containsKey(key)) {
map.put(key, new ArrayList<String>());
}
map.get(key).add(s);
}
return new ArrayList<List<String>>(map.values());
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/amazon/Subsets.java | company/amazon/Subsets.java | // Given a set of distinct integers, nums, return all possible subsets.
// Note: The solution set must not contain duplicate subsets.
// For example,
// If nums = [1,2,3], a solution is:
// [
// [3],
// [1],
// [2],
// [1,2,3],
// [1,3],
// [2,3],
// [1,2],
// []
// ]
public class Subsets {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
recurse(result, nums, new Stack<>(), 0);
return result;
}
private void recurse(List<List<Integer>> result, int[] nums, Stack path, int position) {
if(position == nums.length) {
result.add(new ArrayList<>(path));
return;
}
path.push(nums[position]);
recurse(result, nums, path, position + 1);
path.pop();
recurse(result, nums, path, position + 1);
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/amazon/WordBreak.java | company/amazon/WordBreak.java | // Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words. You may assume the dictionary does not contain duplicate words.
// For example, given
// s = "leetcode",
// dict = ["leet", "code"].
// Return true because "leetcode" can be segmented as "leet code".
public class WordBreak {
public boolean wordBreak(String s, Set<String> wordDict) {
boolean[] dp = new boolean[s.length() + 1];
dp[0] = true;
for(int i = 1; i <= s.length(); i++) {
for(int j = 0; j < i; j++) {
if(dp[j] && wordDict.contains(s.substring(j, i))) {
dp[i] = true;
break;
}
}
}
return dp[s.length()];
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/amazon/TrappingRainWater.java | company/amazon/TrappingRainWater.java | // Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
// For example,
// Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.
public class TrappingRainWater {
public int trap(int[] height) {
int water = 0;
int leftIndex = 0;
int rightIndex = height.length - 1;
int leftMax = 0;
int rightMax = 0;
while(leftIndex <= rightIndex) {
leftMax = Math.max(leftMax, height[leftIndex]);
rightMax = Math.max(rightMax, height[rightIndex]);
if(leftMax < rightMax) {
water += leftMax - height[leftIndex];
leftIndex++;
} else {
water += rightMax - height[rightIndex];
rightIndex--;
}
}
return water;
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/amazon/PalindromeLinkedList.java | company/amazon/PalindromeLinkedList.java | /**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class PalindromeLinkedList {
public boolean isPalindrome(ListNode head) {
if(head == null || head.next == null) {
return true;
}
Stack<Integer> stack = new Stack<Integer>();
ListNode fast = head;
ListNode slow = head;
while(fast != null && fast.next != null) {
stack.push(slow.val);
fast = fast.next.next;
slow = slow.next;
}
if(fast != null) {
slow = slow.next;
}
while(slow != null) {
if(stack.pop() != slow.val) {
return false;
}
slow = slow.next;
}
return true;
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/amazon/LowestCommonAncestorOfABinaryTree.java | company/amazon/LowestCommonAncestorOfABinaryTree.java | // Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
// According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”
// _______3______
// / \
// ___5__ ___1__
// / \ / \
// 6 _2 0 8
// / \
// 7 4
// For example, the lowest common ancestor (LCA) of nodes 5 and 1 is 3. Another example is LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class LowestCommonAncestorOfABinaryTree {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root == null || root == p || root == q) {
return root;
}
TreeNode left = lowestCommonAncestor(root.left, p, q);
TreeNode right = lowestCommonAncestor(root.right, p, q);
if(left != null && right != null) {
return root;
}
return left == null ? right : left;
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/amazon/BinaryTreeLevelOrderTraversal.java | company/amazon/BinaryTreeLevelOrderTraversal.java | // Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
// For example:
// Given binary tree [3,9,20,null,null,15,7],
// 3
// / \
// 9 20
// / \
// 15 7
// return its level order traversal as:
// [
// [3],
// [9,20],
// [15,7]
// ]
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class BinaryTreeLevelOrderTraversal {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
if(root == null) {
return result;
}
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.add(root);
List<Integer> tempList = new ArrayList<Integer>();
tempList.add(root.val);
result.add(tempList);
while(!queue.isEmpty()) {
Queue<TreeNode> currentLevel = new LinkedList<TreeNode>();
List<Integer> list = new ArrayList<Integer>();
while(!queue.isEmpty()) {
TreeNode current = queue.remove();
if(current.left != null) {
currentLevel.add(current.left);
list.add(current.left.val);
}
if(current.right != null) {
currentLevel.add(current.right);
list.add(current.right.val);
}
}
if(list.size() > 0) {
result.add(list);
}
queue = currentLevel;
}
return result;
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/amazon/RotateImage.java | company/amazon/RotateImage.java | // You are given an n x n 2D matrix representing an image.
// Rotate the image by 90 degrees (clockwise).
// Follow up:
// Could you do this in-place?
public class RotateImage {
public void rotate(int[][] matrix) {
for(int i = 0; i < matrix.length; i++) {
for(int j = 0; j < i; j++) {
int temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
for(int i = 0; i < matrix.length; i++) {
for(int j = 0; j < matrix[0].length / 2; j++) {
int temp = matrix[i][j];
matrix[i][j] = matrix[i][matrix[0].length - 1 - j];
matrix[i][matrix[0].length - 1 - j] = temp;
}
}
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/amazon/ValidateBinarySearchTree.java | company/amazon/ValidateBinarySearchTree.java | // Given a binary tree, determine if it is a valid binary search tree (BST).
// Assume a BST is defined as follows:
// The left subtree of a node contains only nodes with keys less than the node's key.
// The right subtree of a node contains only nodes with keys greater than the node's key.
// Both the left and right subtrees must also be binary search trees.
// Example 1:
// 2
// / \
// 1 3
// Binary tree [2,1,3], return true.
// Example 2:
// 1
// / \
// 2 3
// Binary tree [1,2,3], return false.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class ValidateBinarySearchTree {
public boolean isValidBST(TreeNode root) {
if(root == null) {
return true;
}
return validBSTRecursive(root, Long.MIN_VALUE, Long.MAX_VALUE);
}
public boolean validBSTRecursive(TreeNode root, long minValue, long maxValue) {
if(root == null) {
return true;
} else if(root.val >= maxValue || root.val <= minValue) {
return false;
} else {
return validBSTRecursive(root.left, minValue, root.val) && validBSTRecursive(root.right, root.val, maxValue);
}
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/uva/OpenSource.java | uva/OpenSource.java | // At an open-source fair held at a major university,
// leaders of open-source projects put sign-up
// sheets on the wall, with the project name at the
// top in capital letters for identification.
// Students then signed up for projects using
// their userids. A userid is a string of lower-case
// letters and numbers starting with a letter.
// The organizer then took all the sheets off the
// wall and typed in the information.
// Your job is to summarize the number of
// students who have signed up for each project.
// Some students were overly enthusiastic and put
// their name down several times for the same
// project. That’s okay, but they should only count
// once. Students were asked to commit to a single
// project, so any student who has signed up for more
// than one project should not count for any project.
// There are at most 10,000 students at the university,
// and at most 100 projects were advertised.
// Input
// The input contains several test cases, each one ending with a line that starts with the digit 1. The last
// test case is followed by a line starting with the digit 0.
// Each test case consists of one or more project sheets. A project sheet consists of a line containing
// the project name in capital letters, followed by the userids of students, one per line.
// Output
// For each test case, output a summary of each project sheet. The summary is one line with the name
// of the project followed by the number of students who signed up. These lines should be printed in
// decreasing order of number of signups. If two or more projects have the same number of signups, they
// should be listed in alphabetical order.
// Sample Input
// UBQTS TXT
// tthumb
// LIVESPACE BLOGJAM
// philton
// aeinstein
// YOUBOOK
// j97lee
// sswxyzy
// j97lee
// aeinstein
// SKINUX
// 1
// 0
// Sample Output
// YOUBOOK 2
// LIVESPACE BLOGJAM 1
// UBQTS TXT 1
// SKINUX 0
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.*;
import static java.lang.Character.isUpperCase;
/**
* Created by kdn251 on 3/7/17.
*/
public class OpenSource {
public static void main(String args[]) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line;
while(!(line = br.readLine()).equals("0")) {
HashMap<String, Integer> projects = new HashMap<String, Integer>();
HashMap<String, String> students = new HashMap<String, String>();
String project = line;
projects.put(project, 0);
while(!(line = br.readLine()).equals("1")) {
if(isUpperCase(line.charAt(0))) {
project = line;
projects.put(project, 0);
}
else {
if(students.containsKey(line)) {
if(students.get(line).equals("")) {
continue;
}
else {
if(!students.get(line).equals(project)) {
projects.put(students.get(line), projects.get(students.get(line)) - 1);
students.put(line, "");
}
}
}
else {
projects.put(project, projects.get(project) + 1);
students.put(line, project);
}
}
}
List<Pair> pairs = new ArrayList<Pair>();
int count = 0;
for(String s : projects.keySet()) {
pairs.add(new Pair(s, projects.get(s)));
}
Collections.sort(pairs,new Comparator<Pair>() {
public int compare(Pair o1, Pair o2) {
if(-Integer.compare(o1.total, o2.total) == 0) {
return o1.name.compareTo(o2.name);
}
return -Integer.compare(o1.total, o2.total);
}
});
for(Pair p : pairs) {
System.out.println(p.name + " " + p.total);
}
}
}
}
class Pair {
String name;
int total;
Pair(String name, int total) {
this.name = name;
this.total = total;
}
} | java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/uva/LightMoreLight.java | uva/LightMoreLight.java | /**
* There is man named ”mabu” for switching on-off light in our University. He switches on-off the lights
* in a corridor. Every bulb has its own toggle switch. That is, if it is pressed then the bulb turns on.
* Another press will turn it off. To save power consumption (or may be he is mad or something else)
* he does a peculiar thing. If in a corridor there is n bulbs, he walks along the corridor back and forth
* n times and in i-th walk he toggles only the switches whose serial is divisable by i. He does not press
* any switch when coming back to his initial position. A i-th walk is defined as going down the corridor
* (while doing the peculiar thing) and coming back again. Now you have to determine what is the final
* condition of the last bulb. Is it on or off?
* Input
* The input will be an integer indicating the n’th bulb in a corridor. Which is less then or equals 232 −1.
* A zero indicates the end of input. You should not process this input.
* Output
* Output ‘yes’ if the light is on otherwise ‘no’, in a single line.
* Sample Input
* 3
* 6241
* 8191
* 0
* Sample Output
* no
* yes
* no
*/
//https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&category=&problem=1051
import java.util.Scanner;
public class LightMoreLight {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
long number = input.nextLong();
while (number != 0) {
if (isAPerfectSquare(number)) {
System.out.println("yes");
} else {
System.out.println("no");
}
number = input.nextLong();
}
}
private static boolean isAPerfectSquare(long number) {
long squareRoot = (long) Math.sqrt(number);
return squareRoot * squareRoot == number;
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/uva/JollyJumpers.java | uva/JollyJumpers.java |
/**
* A sequence of n > 0 integers is called a jolly jumper if the absolute values of the difference between
* successive elements take on all the values 1 through n − 1. For instance,
* 1 4 2 3
* is a jolly jumper, because the absolutes differences are 3, 2, and 1 respectively. The definition implies
* that any sequence of a single integer is a jolly jumper. You are to write a program to determine whether
* or not each of a number of sequences is a jolly jumper.
* Input
* Each line of input contains an integer n ≤ 3000 followed by n integers representing the sequence.
* Output
* For each line of input, generate a line of output saying ‘Jolly’ or ‘Not jolly’.
* Sample Input
* 4 1 4 2 3
* 5 1 4 2 -1 6
* Sample Output
* Jolly
* Not jolly
*/
//https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=979
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class JollyJumpers {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (input.hasNext()) {
Set<Integer> numbersAlreadyAdded = new HashSet<Integer>();
int numberOfElements = input.nextInt();
int[] numbers = new int[numberOfElements];
for (int i = 0; i < numberOfElements; i++) {
numbers[i] = input.nextInt();
}
for (int i = 0; i < numberOfElements - 1; i++) {
int difference = Math.abs(numbers[i] - numbers[i + 1]);
if (difference > 0 && difference < numberOfElements) {
numbersAlreadyAdded.add(difference);
}
}
if (numbersAlreadyAdded.size() == (numberOfElements - 1)) {
System.out.println("Jolly");
} else {
System.out.println("Not jolly");
}
}
}
} | java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/uva/ArchaeologistsDilemma.java | uva/ArchaeologistsDilemma.java | /**
* An archeologist seeking proof of the presence of extraterrestrials in the Earth’s past, stumbles upon a
* partially destroyed wall containing strange chains of numbers. The left-hand part of these lines of digits
* is always intact, but unfortunately the right-hand one is often lost by erosion of the stone. However,
* she notices that all the numbers with all its digits intact are powers of 2, so that the hypothesis that
* all of them are powers of 2 is obvious. To reinforce her belief, she selects a list of numbers on which it
* is apparent that the number of legible digits is strictly smaller than the number of lost ones, and asks
* you to find the smallest power of 2 (if any) whose first digits coincide with those of the list.
* Thus you must write a program such that given an integer, it determines (if it exists) the smallest
* exponent E such that the first digits of 2
* E coincide with the integer (remember that more than half of
* the digits are missing).
* Input
* It is a set of lines with a positive integer N not bigger than 2147483648 in each of them.
* Output
* For every one of these integers a line containing the smallest positive integer E such that the first digits
* of 2
* E are precisely the digits of N, or, if there is no one, the sentence ‘no power of 2’.
* Sample Input
* 1
* 2
* 10
* Sample Output
* 7
* 8
* 20
*/
//https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=642
import java.io.IOException;
import java.util.Scanner;
public class ArchaeologistsDilemma {
public static final boolean DEBUG = true;
public static final boolean DEBUG_INPUT = true;
final static double LOG2 = Math.log(2.0);
final static double LOG2_10 = Math.log(10) / LOG2;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (true) {
long N = input.nextLong();
int k = (N + "").length() + 1;
long lowerBound = (long) ((Math.log(N) / LOG2) + k * LOG2_10);
long upperBound = (long) ((Math.log(N + 1) / LOG2) + k * LOG2_10);
while (lowerBound == upperBound) {
k++;
lowerBound = (long) ((Math.log(N) / LOG2) + k * LOG2_10);
upperBound = (long) ((Math.log(N + 1) / LOG2) + k * LOG2_10);
}
System.out.println(upperBound);
}
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/uva/SplittingNumbers.java | uva/SplittingNumbers.java | // We define the operation of splitting
// a binary number n into two numbers
// a(n), b(n) as follows. Let 0 ≤ i1 < i2 <
// . . . < ik be the indices of the bits (with
// the least significant bit having index 0) in
// n that are 1. Then the indices of the bits
// of a(n) that are 1 are i1, i3, i5, . . . and the
// indices of the bits of b(n) that are 1 are
// i2, i4, i6, . . .
// For example, if n is 110110101 in binary
// then, again in binary, we have a =
// 010010001 and b = 100100100.
// Input
// Each test case consists of a single integer
// n between 1 and 231 − 1 written in standard decimal (base 10) format on a single line. Input is
// terminated by a line containing ‘0’ which should not be processed.
// Output
// The output for each test case consists of a single line, containing the integers a(n) and b(n) separated
// by a single space. Both a(n) and b(n) should be written in decimal format.
// Sample Input
// 6
// 7
// 13
// 0
// Sample Output
// 2 4
// 5 2
// 9 4
/**
* Created by kdn251 on 2/10/17.
*/
import java.util.*;
import java.io.*;
public class SplittingNumbers {
public static void main(String args[]) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line;
while((line = br.readLine()) != null) {
//read number
int number = Integer.parseInt(line);
//terminate if number is zero
if(number == 0) break;
//intialize variables
int count = 0;
int a = 0;
int b = 0;
while(number > 0) {
//get lowest set bit
int currentBit = number ^ (number & (number - 1));
//if count is even or a with current bit
if(count % 2 == 0) {
a |= currentBit;
}
//if count is odd or b with current bit
else {
b |= currentBit;
}
//increment count
count++;
//clear lowest set bit for next iteration
number &= (number - 1);
}
//print a and b
System.out.println(a + " " + b);
}
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/uva/NumberTheoryForNewbies.java | uva/NumberTheoryForNewbies.java | /**
* Given any positive integer, if we permute its digits, the difference between the number we get and the
* given number will always be divisible by 9.
* For example, if the given number is 123, we may rearrange the digits to get 321. The difference =
* 321 - 123 = 198, which is a multiple of 9 (198 = 9 × 22).
* We can prove this fact fairly easily, but since we are not having a maths contest, we instead try to
* illustrate this fact with the help of a computer program.
* Input
* Each line of input gives a positive integer n (≤ 2000000000). You are to find two integers a and b
* formed by rearranging the digits of n, such that a − b is maximum. a and b should NOT have leading
* zeros.
* Output
* You should then show that a − b is a multiple of 9, by expressing it as ‘9 * k’, where k is an integer.
* See the sample output for the correct output format.
* Sample Input
* 123
* 2468
* Sample Output
* 321 - 123 = 198 = 9 * 22
* 8642 - 2468 = 6174 = 9 * 686
*/
//https://uva.onlinejudge.org/index.php?option=onlinejudge&Itemid=99999999&page=show_problem&category=&problem=2366
import java.util.Arrays;
import java.util.Scanner;
public class NumberTheoryForNewbies {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (input.hasNextLong()) {
String inputValue = input.nextLine();
StringBuilder minimal = new StringBuilder();
StringBuilder maximal = new StringBuilder();
char[] characters = inputValue.toCharArray();
int length = characters.length;
Arrays.sort(characters);
int index;
for (index = 0; index < length; index++) {
if (characters[index] != '0') {
break;
}
}
if (index != 0) {
characters[0] = characters[index];
characters[index] = '0';
}
for (int i = 0; i < length; i++) {
minimal.append(characters[i]);
}
Arrays.sort(characters);
for (int i = length - 1; i > -1; i--) {
maximal.append(characters[i]);
}
long maximalNumber = Long.valueOf(maximal.toString());
long minimalNumber = Long.valueOf(minimal.toString());
long difference = maximalNumber - minimalNumber;
System.out.println(maximal + " - " + minimal + " = " + difference
+ " = 9 * " + (difference / 9));
}
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/uva/SimplifyingFractions.java | uva/SimplifyingFractions.java | /**
* You are to write a program that reduces a fraction into its lowest terms.
* Input
* The first line of the input file gives the number of test cases N (≤ 20). Each of the following N lines
* contains a fraction in the form of p/q (1 ≤ p, q ≤ 1030).
* Output
* For each test case, output the fraction after simplification.
* Sample Input
* 4
* 1 / 2
* 2 / 4
* 3 / 3
* 4 / 2
* Sample Output
* 1 / 2
* 1 / 2
* 1 / 1
* 2 / 1
*/
//https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1755
import java.math.BigInteger;
import java.util.Scanner;
public class SimplifyingFractions {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int numberOfTestCases = input.nextInt();
while (numberOfTestCases != 0) {
String pAsString = input.next();
input.next();
String qAsString = input.next();
BigInteger p = new BigInteger(pAsString);
BigInteger q = new BigInteger(qAsString);
BigInteger greatestCommonDivisor = p.gcd(q);
if (!greatestCommonDivisor.equals(BigInteger.ONE)) {
p = p.divide(greatestCommonDivisor);
q = q.divide(greatestCommonDivisor);
}
System.out.println(p + " / " + q);
numberOfTestCases--;
}
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/uva/VeryEasy.java | uva/VeryEasy.java | /**
* Most of the times, the students of Computer Science & Engineering of BUET deal with bogus, tough and
* very complex formulae. That is why, sometimes, even for a easy problem they think very hard and make
* the problem much complex to solve. But, the team members of the team “BUET PESSIMISTIC”
* are the only exceptions. Just like the opposite manner, they treat every hard problem as easy and so
* cannot do well in any contest. Today, they try to solve a series but fail for treating it as hard. Let
* them help.
* Input
* Just try to determine the answer for the following series
* ∑
* N
* i=1
* iAi
* You are given the value of integers N and A (1 ≤ N ≤ 150, 0 ≤ A ≤ 15).
* Output
* For each line of the input, your correct program should output the integer value of the sum in separate
* lines for each pair of values of N and A.
* Sample Input
* 3 3
* 4 4
* Sample Output
* 102
* 1252
*/
//https://uva.onlinejudge.org/index.php?option=onlinejudge&Itemid=99999999&page=show_problem&category=&problem=1464
import java.math.BigInteger;
import java.util.Scanner;
public class VeryEasy {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (input.hasNext()) {
BigInteger sum = BigInteger.ZERO;
int N = input.nextInt();
int A = input.nextInt();
BigInteger aAsBigInteger = BigInteger.valueOf(A);
BigInteger product = BigInteger.ONE;
for (int i = 1; i < N + 1; i++) {
product = BigInteger.valueOf(i).multiply(aAsBigInteger.pow(i));
sum = sum.add(product);
}
System.out.println(sum);
}
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/uva/Newspaper.java | uva/Newspaper.java | /**
* News agency pays money for articles according to some rules. Each character has its own value (some
* characters may have value equals to zero). Author gets his payment as a sum of all character’s values
* in the article. You have to determine the amount of money that news agency must pay to an author.
* Input
* The first line contains integer N (0 < N ≤ 5), it is a number of tests. Each test describes an integer
* K (0 < K ≤ 100), the number of paid characters. On next K lines there are table of paid characters
* and its values (character values are written in cents). If character can not be found in the table, then
* its value is equal to zero. Next, there is integer M (0 < M ≤ 150000). Next M lines contain an article
* itself. Each line can be up to 10000 characters length. Be aware of a large input size, the whole input
* file is about 7MB.
* Output
* For each test print how much money publisher must pay for an article in format ‘x.yy$’. Where x is
* a number of dollars without leading zeros, and yy number of cents with one leading zero if necessary.
* Examples: ‘3.32$’, ‘13.07$’, ‘71.30$’, ‘0.09$’.
* Sample Input
* 1
* 7
* a 3
* W 10
* A 100
* , 10
* k 7
* . 3
* I 13
* 7
* ACM International Collegiate Programming Contest (abbreviated
* as ACM-ICPC or just ICPC) is an annual multi-tiered competition
* among the universities of the world. The ICPC challenges students
* to set ever higher standards of excellence for themselves
* through competition that rewards team work, problem analysis,
* and rapid software development.
* From Wikipedia.
* Sample Output
* 3.74$
*/
//https://uva.onlinejudge.org/index.php?option=onlinejudge&page=show_problem&problem=2315
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Newspaper {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int numberOfTestCases = input.nextInt();
while (numberOfTestCases != 0) {
Map<String, Integer> values = new HashMap<String, Integer>();
int numberOfValuableCharacters = input.nextInt();
while (numberOfValuableCharacters != 0) {
values.put(input.next(), input.nextInt());
numberOfValuableCharacters--;
}
int numberOfLines = input.nextInt();
input.nextLine();
double sum = 0;
while (numberOfLines != 0) {
String textAsString = input.nextLine();
for (int i = 0; i < textAsString.length(); i++) {
String c = textAsString.charAt(i) + "";
if (values.containsKey(c)) {
sum = sum + values.get(c);
}
}
numberOfLines--;
}
sum = sum / 100;
DecimalFormat formatter = new DecimalFormat("0.00");
String sumFormatted = formatter.format(sum);
System.out.println(sumFormatted + "$");
numberOfTestCases--;
}
}
} | java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/uva/BigMod.java | uva/BigMod.java | /**
* Calculate
* R := B
* P mod M
* for large values of B, P, and M using an efficient algorithm. (That’s right, this problem has a time
* dependency !!!.)
* Input
* The input will contain several test cases, each of them as described below. Consecutive test cases are
* separated by a single blank line.
* Three integer values (in the order B, P, M) will be read one number per line. B and P are integers
* in the range 0 to 2147483647 inclusive. M is an integer in the range 1 to 46340 inclusive.
* Output
* For each test, the result of the computation. A single integer on a line by itself.
* Sample Input
* 3
* 18132
* 17
* 17
* 1765
* 3
* 2374859
* 3029382
* 36123
* Sample Output
* 13
* 2
* 13195
*/
//https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=727&page=show_problem&problem=310
import java.math.BigInteger;
import java.util.Scanner;
public class BigMod {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (input.hasNext()) {
BigInteger b = input.nextBigInteger();
BigInteger p = input.nextBigInteger();
BigInteger m = input.nextBigInteger();
System.out.println(b.modPow(p, m));
}
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/uva/WhoSaidCrisis.java | uva/WhoSaidCrisis.java | /**
* The company Assistance for Critical Moments (ACM) is helping other companies to overcome the
* current economical crisis. As experts in computing machinery, their job is to calculate the cost/benefit
* balance of the other companies. They receive two numbers, indicating the total amount of benefits and
* costs, and they have to compute the final balance.
* You have to solve the complex business problem of computing balances. You are given two positive
* integer numbers, corresponding to the benefits and the costs. You have to obtain the total balance,
* i.e., the difference between benefits and costs.
* Input
* The first line of the input contains an integer indicating the number of test cases.
* For each test case, there is a line with two positive integer numbers, A and B, corresponding to the
* benefits and the costs, respectively. Both numbers are between 0 and a googol (10100) to the power of
* a hundred.
* Output
* For each test case, the output should consist of a line indicating the balance: A − B.
* Sample Input
* 4
* 10 3
* 4 9
* 0 8
* 5 2
* Sample Output
* 7
* -5
* -8
* 3
*/
//https://uva.onlinejudge.org/index.php?option=onlinejudge&Itemid=99999999&page=show_problem&category=&problem=2443
import java.math.BigInteger;
import java.util.Scanner;
public class WhoSaidCrisis {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int numberOfTestCases = input.nextInt();
while (numberOfTestCases != 0) {
BigInteger first = input.nextBigInteger();
BigInteger second = input.nextBigInteger();
System.out.println(first.subtract(second));
numberOfTestCases--;
}
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/uva/BasicallySpeaking.java | uva/BasicallySpeaking.java | /**
* The Really Neato Calculator Company, Inc. has recently hired your team to help design their Super
* Neato Model I calculator. As a computer scientist you suggested to the company that it would be neato
* if this new calculator could convert among number bases. The company thought this was a stupendous
* idea and has asked your team to come up with the prototype program for doing base conversion. The
* project manager of the Super Neato Model I calculator has informed you that the calculator will have
* the following neato features:
* • It will have a 7-digit display.
* • Its buttons will include the capital letters A through F in addition to the digits 0 through 9.
* • It will support bases 2 through 16.
* Input
* The input for your prototype program will consist of one base conversion per line. There will be three
* numbers per line. The first number will be the number in the base you are converting from. It may have
* leading ‘0’s. The second number is the base you are converting from. The third number is the base you
* are converting to. There will be one or more blanks surrounding (on either side of) the numbers. There
* are several lines of input and your program should continue to read until the end of file is reached.
* Output
* The output will only be the converted number as it would appear on the display of the calculator.
* The number should be right justified in the 7-digit display. If the number is to large to appear on the
* display, then print ‘ERROR’ (without the quotes) right justified in the display.
* Sample Input
* 1111000 2 10
* 1111000 2 16
* 2102101 3 10
* 2102101 3 15
* 12312 4 2
* 1A 15 2
* ABCD 16 15
* 03 13 10
* Sample Output
* 120
* 78
* 1765
* 7CA
* ERROR
* 11001
* D071
* 3
*/
//https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&category=&problem=325
import java.math.BigInteger;
import java.util.Scanner;
public class BasicallySpeaking {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (input.hasNext()) {
String numberAsString = input.next();
int fromBase = input.nextInt();
int toBase = input.nextInt();
BigInteger number = new BigInteger(numberAsString, fromBase);
String numberThatIsPrinted = number.toString(toBase);
String answer = numberThatIsPrinted.toUpperCase();
if (numberThatIsPrinted.length() > 7) {
answer = "ERROR";
}
System.out.printf("%7s\n", answer);
}
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/uva/Friends.java | uva/Friends.java | // There is a town with N citizens. It is known that some pairs of people are friends. According to the
// famous saying that “The friends of my friends are my friends, too” it follows that if A and B are friends
// and B and C are friends then A and C are friends, too.
// Your task is to count how many people there are in the largest group of friends.
// Input
// Input consists of several datasets. The first line of the input consists of a line with the number of test
// cases to follow.
// The first line of each dataset contains tho numbers N and M, where N is the number of town’s
// citizens (1 ≤ N ≤ 30000) and M is the number of pairs of people (0 ≤ M ≤ 500000), which are known
// to be friends. Each of the following M lines consists of two integers A and B (1 ≤ A ≤ N, 1 ≤ B ≤ N,
// A ̸= B) which describe that A and B are friends. There could be repetitions among the given pairs
// Output
// The output for each test case should contain (on a line by itself) one number denoting how many people
// there are in the largest group of friends on a line by itself.
// Sample Input
// 2
// 3 2
// 1 2
// 2 3
// 10 12
// 1 2
// 3 1
// 3 4
// 5 4
// 3 5
// 4 6
// 5 2
// 2 1
// 7 1
// 1 2
// 9 10
// 8 9
// Sample Output
// 3
// 7
import java.io.*;
import java.util.*;
/**
* Created by kdn251 on 2/15/17.
*/
public class Friends {
//initialize globals to track each individual person and their relationships
public static int[] people = new int[30001];
public static int[] relationships = new int[50001];
public static void main(String args[]) throws Exception {
//initialize buffered reader
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
//store number of test cases
int testCases = Integer.parseInt(line);
for(int i = 0; i < testCases; i++) {
//determine number of people and pairs of people (N and M)
String[] info = br.readLine().split(" ");
int numberOfPeople = Integer.parseInt(info[0]);
int numberOfRelationship = Integer.parseInt(info[1]);
startUnion(numberOfPeople, people, relationships);
//iterate through all relationships
for(int j = 0; j < numberOfRelationship ; j++) {
//split current line to determine person and friend
String[] currentLine = br.readLine().split(" ");
int person = Integer.parseInt(currentLine[0]);
int friend = Integer.parseInt(currentLine[1]);
union(person, friend);
}
//initialize maxGroup to one because each group has one person initially
int maxGroup = 1;
//iterate through relationships to find the largest group
for(int j = 0; j <= numberOfPeople; j++) {
//update max as needed
maxGroup = relationships[j] > maxGroup ? relationships[j] : maxGroup;
}
//print result
System.out.println(maxGroup);
}
}
public static void startUnion(int numberOfPeople, int[] people, int[] relationships) {
for(int i = 0; i <= numberOfPeople; i++) {
//initialize each individual person
people[i] = i;
//each person initially has a group of one (themselves)
relationships[i] = 1;
}
}
public static void union(int person, int friend) {
//find parents in tree
person = find(person);
friend = find(friend);
if(person != friend) {
//add connection between person and friend
join(person, friend);
}
}
public static int find(int person) {
//traverse parents of tree if possible
if(people[person] != person) {
people[person] = find(people[person]);
}
return people[person];
}
public static void join(int person, int friend) {
//find larger group of the two and make sure both person and friend point to it
if(relationships[person] > relationships[friend]) {
relationships[person] += relationships[friend];
people[friend] = person;
}
else {
relationships[friend] += relationships[person];
people[person] = friend;
}
}
}
//source: https://github.com/morris821028/UVa/blob/master/volume106/10608%20-%20Friends.cpp#L27
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/uva/VirtualFriends.java | uva/VirtualFriends.java | // These days, you can do all sorts of things online. For example, you can use various websites to make
// virtual friends. For some people, growing their social network (their friends, their friends’ friends, their
// friends’ friends’ friends, and so on), has become an addictive hobby. Just as some people collect stamps,
// other people collect virtual friends.
// Your task is to observe the interactions on such a website and keep track of the size of each person’s
// network.
// Assume that every friendship is mutual. If Fred is Barney’s friend, then Barney is also Fred’s friend.
// Input
// The first line of input contains one integer specifying the number of test cases to follow. Each test case
// begins with a line containing an integer F, the number of friendships formed, which is no more than
// 100 000. Each of the following F lines contains the names of two people who have just become friends,
// separated by a space. A name is a string of 1 to 20 letters (uppercase or lowercase).
// Output
// Whenever a friendship is formed, print a line containing one integer, the number of people in the social
// network of the two people who have just become friends
// Sample Input
// 1
// 3
// Fred Barney
// Barney Betty
// Betty Wilma
// Sample Output
// 2
// 3
// 4
import java.io.*;
import java.util.Arrays;
import java.util.HashMap;
/**
* Created by kdn251 on 3/7/17.
*/
public class VirtualFriends {
public static int[] people = new int[1000001];
public static int[] relationships = new int[1000001];
public static void main(String args[]) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int cases = Integer.parseInt(br.readLine());
while(cases-- > 0) {
startUnion(people.length);
HashMap<String, Integer> map = new HashMap<String, Integer>();
int friendships = Integer.parseInt(br.readLine());
int numberOfPeople = 0;
for(int i = 0; i < friendships; i++) {
String[] line = br.readLine().split("\\s+");
String x = line[0];
String y = line[1];
if (x.equals(y)) {
System.out.println(1);
continue;
}
if (!map.containsKey(x)) {
map.put(x, ++numberOfPeople);
}
if (!map.containsKey(y)) {
map.put(y, ++numberOfPeople);
}
//print answer for current test case
System.out.println(union(map.get(x), map.get(y)));
}
}
}
public static void startUnion(int numberOfPeople) {
for(int i = 0; i < numberOfPeople; i++) {
//initialize each individual person
people[i] = i;
//each person initially has a group of one (themselves)
relationships[i] = 1;
}
}
public static int union(int person, int friend) {
//find parents in tree
person = find(person);
friend = find(friend);
if(person != friend) {
//add connection between person and friend
//find larger group of the two and make sure both person and friend point to it
if(relationships[person] > relationships[friend]) {
relationships[person] += relationships[friend];
people[friend] = person;
return relationships[person];
}
else {
relationships[friend] += relationships[person];
people[person] = friend;
return relationships[friend];
}
}
return relationships[person];
}
public static int find(int person) {
//traverse parents of tree if possible
if(people[person] != person) {
people[person] = find(people[person]);
}
return people[person];
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/uva/SkewBinary.java | uva/SkewBinary.java | /**
* When a number is expressed in decimal, the k-th digit represents a multiple of 10k. (Digits are numbered
* from right to left, where the least significant digit is number 0.) For example,
* 8130710 = 8 × 104 + 1 × 103 + 3 × 102 + 0 × 101 + 7 × 100 = 80000 + 1000 + 300 + 0 + 7 = 81307.
* When a number is expressed in binary, the k-th digit represents a multiple of 2
* k. For example,
* 100112 = 1 × 2
* 4 + 0 × 2
* 3 + 0 × 2
* 2 + 1 × 2
* 1 + 1 × 2
* 0 = 16 + 0 + 0 + 2 + 1 = 19.
* In skew binary, the k-th digit represents a multiple of 2
* k+1 − 1. The only possible digits are 0
* and 1, except that the least-significant nonzero digit can be a 2. For example,
* 10120skew = 1×(25 −1)+ 0×(24 −1)+ 1×(23 −1)+ 2×(22 −1)+ 0×(21 −1) = 31+ 0+ 7+ 6+ 0 = 44.
* The first 10 numbers in skew binary are 0, 1, 2, 10, 11, 12, 20, 100, 101, and 102. (Skew binary is
* useful in some applications because it is possible to add 1 with at most one carry. However, this has
* nothing to do with the current problem.)
* Input
* The input file contains one or more lines, each of which contains an integer n. If n = 0 it signals the
* end of the input, and otherwise n is a nonnegative integer in skew binary.
* Output
* For each number, output the decimal equivalent. The decimal value of n will be at most 2
* 31 − 1 =
* 2147483647.
* Sample Input
* 10120
* 200000000000000000000000000000
* 10
* 1000000000000000000000000000000
* 11
* 100
* 11111000001110000101101102000
* 0
* Sample Output
* 44
* 2147483646
* 3
* 2147483647
* 4
* 7
* 1041110737
*/
//https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=516
import java.math.BigInteger;
import java.util.Scanner;
public class SkewBinary {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (true) {
BigInteger number = input.nextBigInteger();
if (number.equals(BigInteger.ZERO)) {
break;
}
int length = (number + "").length();
BigInteger sum = BigInteger.ZERO;
for (int i = 0; i < length; i++) {
BigInteger mod10 = number.mod(BigInteger.TEN);
BigInteger insideBrackets = BigInteger.valueOf((long) (Math
.pow(2, i + 1) - 1));
sum = sum.add((mod10).multiply(insideBrackets));
number = number.divide(BigInteger.TEN);
}
System.out.println(sum);
}
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/uva/PrimeFactors.java | uva/PrimeFactors.java | /**
* The most relevant definition for this problem is 2a: An integer g > 1 is said to be prime if and only
* if its only positive divisors are itself and one (otherwise it is said to be composite). For example, the
* number 21 is composite; the number 23 is prime. Note that the decompositon of a positive number g
* into its prime factors, i.e.,
* g = f1 × f2 × · · · × fn
* is unique if we assert that fi > 1 for all i and fi ≤ fj for i < j.
* One interesting class of prime numbers are the so-called Mersenne primes which are of the form
* 2
* p − 1. Euler proved that 2
* 31 − 1 is prime in 1772 — all without the aid of a computer.
* Input
* The input will consist of a sequence of numbers. Each line of input will contain one number g in the
* range −2
* 31 < g < 2
* 31, but different of -1 and 1. The end of input will be indicated by an input line
* having a value of zero.
* Output
* For each line of input, your program should print a line of output consisting of the input number and
* its prime factors. For an input number g > 0, g = f1 × f2 × · · · × fn, where each fi
* is a prime number
* greater than unity (with fi ≤ fj for i < j), the format of the output line should be
* g = f1 x f2 x . . . x fn
* When g < 0, if | g |= f1 × f2 × · · · × fn, the format of the output line should be
* g = -1 x f1 x f2 x . . . x fn
* Sample Input
* -190
* -191
* -192
* -193
* -194
* 195
* 196
* 197
* 198
* 199
* 200
* 0
* Sample Output
* -190 = -1 x 2 x 5 x 19
* -191 = -1 x 191
* -192 = -1 x 2 x 2 x 2 x 2 x 2 x 2 x 3
* -193 = -1 x 193
* -194 = -1 x 2 x 97
* 195 = 3 x 5 x 13
* 196 = 2 x 2 x 7 x 7
* 197 = 197
* 198 = 2 x 3 x 3 x 11
* 199 = 199
* 200 = 2 x 2 x 2 x 5 x 5
*/
//https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=524
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class PrimeFactors {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int number = input.nextInt();
boolean[] isPrime = generatePrimeNumbers();
while (number != 0) {
boolean isNegative = false;
if (number < 0) {
isNegative = true;
number = Math.abs(number);
}
int originalNumber = number;
formatOutput(originalNumber, sieveOfEratosthenes(isPrime, originalNumber), isNegative);
number = input.nextInt();
}
}
public static List<Integer> sieveOfEratosthenes(boolean[] isPrime, int number) {
List<Integer> primeFactors = new ArrayList<Integer>();
int squareRootOfOriginalNumber = (int) Math.sqrt(number);
for (int i = 2; i <= squareRootOfOriginalNumber; i++) {
if (isPrime[i]) {
while (number % i == 0) {
primeFactors.add(i);
number = number / i;
}
}
}
if (number != 1) {
primeFactors.add(number);
}
return primeFactors;
}
static void formatOutput(int number, List<Integer> primeFactors, boolean isNegative) {
if (isNegative) {
number *= -1;
}
StringBuilder output = new StringBuilder(number + " = ");
int numberOfPrimeFactors = primeFactors.size();
if (numberOfPrimeFactors == 1) {
if (isNegative) {
output.append("-1 x " + (number * (-1)));
} else {
output.append(number);
}
} else {
Collections.sort(primeFactors);
if (isNegative) {
output.append("-1 x ");
}
for (int i = 0; i < numberOfPrimeFactors - 1; i++) {
output.append(primeFactors.get(i) + " x ");
}
output.append(primeFactors.get(numberOfPrimeFactors - 1));
}
System.out.println(output);
}
static boolean[] generatePrimeNumbers() {
int number = (int) Math.sqrt(Integer.MAX_VALUE);
boolean[] isPrime = new boolean[number + 1];
for (int i = 2; i < number + 1; i++) {
isPrime[i] = true;
}
for (int factor = 2; factor * factor < number + 1; factor++) {
if (isPrime[factor]) {
for (int j = factor; j * factor < number + 1; j++) {
isPrime[j * factor] = false;
}
}
}
return isPrime;
}
} | java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/uva/MultipleOfSeventeen.java | uva/MultipleOfSeventeen.java | /**
* Theorem: If you drop the last digit d of an integer n (n ≥ 10), subtract 5d from the
* remaining integer, then the difference is a multiple of 17 if and only if n is a multiple of 17.
* For example, 34 is a multiple of 17, because 3-20=-17 is a multiple of 17; 201 is not a multiple of
* 17, because 20-5=15 is not a multiple of 17.
* Given a positive integer n, your task is to determine whether it is a multiple of 17.
* Input
* There will be at most 10 test cases, each containing a single line with an integer n (1 ≤ n ≤ 10100).
* The input terminates with n = 0, which should not be processed.
* Output
* For each case, print 1 if the corresponding integer is a multiple of 17, print 0 otherwise.
* Sample Input
* 34
* 201
* 2098765413
* 1717171717171717171717171717171717171717171717171718
* 0
* Sample Output
* 1
* 0
* 1
* 0
*/
//https://uva.onlinejudge.org/index.php?option=onlinejudge&Itemid=99999999&page=show_problem&category=&problem=3001
import java.math.BigInteger;
import java.util.Scanner;
public class MultipleOfSeventeen {
private static final BigInteger BIGINTEGER_FIVE = new BigInteger("5");
private static final BigInteger BIGINTEGER_SEVENTEEN = new BigInteger("17");
private static final BigInteger BIGINTEGER_ZERO = new BigInteger("0");
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (input.hasNext()) {
BigInteger number = input.nextBigInteger();
if (number.equals(BIGINTEGER_ZERO)) {
break;
}
BigInteger lastDigit = number.mod(BigInteger.TEN);
number = number.divide(BigInteger.TEN);
BigInteger product5D = lastDigit.multiply(BIGINTEGER_FIVE);
BigInteger difference = number.subtract(product5D);
if (difference.mod(BIGINTEGER_SEVENTEEN).equals(BIGINTEGER_ZERO)) {
System.out.println("1");
} else {
System.out.println("0");
}
}
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/uva/Ants.java | uva/Ants.java | // An army of ants walk on a horizontal pole of length l cm, each with a constant speed of 1 cm/s. When
// a walking ant reaches an end of the pole, it immediatelly falls off it. When two ants meet they turn
// back and start walking in opposite directions. We know the original positions of ants on the pole,
// unfortunately, we do not know the directions in which the ants are walking. Your task is to compute
// the earliest and the latest possible times needed for all ants to fall off the pole.
// Input
// The first line of input contains one integer giving the number of cases that follow. The data for each
// case start with two integer numbers: the length of the pole (in cm) and n, the number of ants residing
// on the pole. These two numbers are followed by n integers giving the position of each ant on the pole
// as the distance measured from the left end of the pole, in no particular order. All input integers are
// not bigger than 1000000 and they are separated by whitespace.
// Output
// For each case of input, output two numbers separated by a single space. The first number is the earliest
// possible time when all ants fall off the pole (if the directions of their walks are chosen appropriately)
// and the second number is the latest possible such time.
// Sample Input
// 2
// 10 3
// 2 6 7
// 214 7
// 11 12 7 13 176 23 191
// Sample Output
// 4 8
// 38 207
import java.util.Scanner;
/**
* Created by kdn251 on 2/22/17.
*/
public class Ants {
public static void main(String args[]) throws Exception {
//initialize buffered reader
Scanner sc = new Scanner(System.in);
//initialize test cases
int testCases = sc.nextInt();
//declare current ant
int currentAnt;
while(testCases > 0) {
//initialize length of rod and number of ants
int length = sc.nextInt();
int numberOfAnts = sc.nextInt();
//initialize min and max to zero
int min = 0;
int max = 0;
//iterate while there are still remaining ants to process
while(numberOfAnts > 0) {
//read in current ant
currentAnt = sc.nextInt();
//calculate whether ant is closer to left side of rod or right side of rod
currentAnt = currentAnt < length - currentAnt ? currentAnt : length - currentAnt;
//update minimum time to most restrictive ant minimum time
if(currentAnt > min) {
min = currentAnt;
}
//update maximum time to most restrictive ant maximum time
if(length - currentAnt > max) {
max = length - currentAnt;
}
//decrement number of ants remaining
numberOfAnts--;
}
//print min and max of current test case
System.out.println(min + " " + max);
//decrement number of test cases remaining
testCases--;
}
}
}
//source: https://github.com/morris821028/UVa/blob/master/volume107/10714%20-%20Ants.cpp | java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/uva/GoldbachConjecture.java | uva/GoldbachConjecture.java | /**
* In 1742, Christian Goldbach, a German amateur mathematician, sent a letter to Leonhard Euler in
* which he made the following conjecture:
* Every number greater than 2 can be written as the sum of three prime numbers.
* Goldbach was considering 1 as a primer number, a convention that is no longer followed. Later on,
* Euler re-expressed the conjecture as:
* Every even number greater than or equal to 4 can be expressed as the sum of two prime
* numbers.
* For example:
* • 8 = 3 + 5. Both 3 and 5 are odd prime numbers.
* • 20 = 3 + 17 = 7 + 13.
* • 42 = 5 + 37 = 11 + 31 = 13 + 29 = 19 + 23.
* Today it is still unproven whether the conjecture is right. (Oh wait, I have the proof of course, but
* it is too long to write it on the margin of this page.)
* Anyway, your task is now to verify Goldbach’s conjecture as expressed by Euler for all even numbers
* less than a million.
* Input
* The input file will contain one or more test cases.
* Each test case consists of one even integer n with 6 ≤ n < 1000000.
* Input will be terminated by a value of 0 for n.
* Output
* For each test case, print one line of the form n = a + b, where a and b are odd primes. Numbers and
* operators should be separated by exactly one blank like in the sample output below. If there is more
* than one pair of odd primes adding up to n, choose the pair where the difference b − a is maximized.
* If there is no such pair, print a line saying ‘Goldbach's conjecture is wrong.’
* Sample Input
* 8
* 20
* 42
* 0
* Sample Output
* 8 = 3 + 5
* 20 = 3 + 17
* 42 = 5 + 37
*/
//https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=484
import java.util.Scanner;
public class GoldbachConjecture {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean[] isPrime = sieveOfEratosthenes(1000000);
int number = input.nextInt();
while (number != 0) {
boolean found = false;
for (int i = 3; i < number && !found; i++) {
if (isPrime[i]) {
int currentPrime = i;
int j = number - currentPrime;
if (isPrime[j]) {
System.out.println(number + " = " + currentPrime
+ " + " + j);
found = true;
}
}
}
if (!found) {
System.out.println("Goldbach's conjecture is wrong.");
}
number = input.nextInt();
}
}
private static boolean[] sieveOfEratosthenes(int number) {
boolean[] isPrime = new boolean[number + 1];
for (int i = 2; i < number + 1; i++) {
isPrime[i] = true;
}
for (int factor = 2; factor * factor <= number; factor++) {
if (isPrime[factor]) {
for (int j = factor; factor * j <= number; j++) {
isPrime[factor * j] = false;
}
}
}
return isPrime;
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/uva/TheHugeOne.java | uva/TheHugeOne.java | /**
* Your girlfriend Marry has some problems with programming task teacher gave her. Since you have
* the great programming skills it won’t be a problem for you to help her. And certainly you don’t want
* Marry to have her time spent on this task because you were planning to go to the cinema with her this
* weekend. If you accomplish this task Marry will be very grateful and will definitely go with you to the
* cinema and maybe even more. So it’s up to you now
* That’s the task she was given:
* Number 0 ≤ M ≤ 101000 is given, and a set S of different numbers from the interval [1;12]. All
* numbers in this set are integers. Number M is said to be wonderful if it is divisible by all numbers in
* set S. Find out whether or not number M is wonderful.
* Input
* First line of input data contains number N (0 < N ≤ 2000). Then N tests follow each described on
* two lines. First line of each test case contains number M. Second line contains the number of elements
* in a set S followed by a space and the numbers in the set. Numbers of this set are separated by a space
* character.
* Output
* Output one line for each test case: ‘M - Wonderful.’, if the number is wonderful or ‘M - Simple.’
* if it is not. Replace M character with the corresponding number. Refer output data for details.
* Sample Input
* 4
* 0
* 12 1 2 3 4 5 6 7 8 9 10 11 12
* 379749833583241
* 1 11
* 3909821048582988049
* 1 7
* 10
* 3 1 2 9
* Sample Output
* 0 - Wonderful.
* 379749833583241 - Wonderful.
* 3909821048582988049 - Wonderful.
* 10 - Simple.
*/
//https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=2319
import java.math.BigInteger;
import java.util.Scanner;
public class TheHugeOne {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int numberOfTestCases = input.nextInt();
while (numberOfTestCases != 0) {
BigInteger M = input.nextBigInteger();
input.nextLine();
String[] elementsLine = input.nextLine().split(" ");
boolean found = false;
for (int i = 1; i < elementsLine.length; i++) {
BigInteger number = new BigInteger(elementsLine[i]);
if (!M.mod(number).equals(BigInteger.ZERO)) {
System.out.println(M + " - Simple.");
found = true;
break;
}
}
if (!found) {
System.out.println(M + " - Wonderful.");
}
numberOfTestCases--;
}
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/uva/TheSettlersOfCatan.java | uva/TheSettlersOfCatan.java | // Within Settlers of Catan, the 1995 German game of the year, players attempt to dominate an island
// by building roads, settlements and cities across its uncharted wilderness.
// You are employed by a software company that just has decided to develop a computer version of
// this game, and you are chosen to implement one of the game’s special rules:
// When the game ends, the player who built the longest road gains two extra victory points.
// The problem here is that the players usually build complex road networks and not just one linear
// path. Therefore, determining the longest road is not trivial (although human players usually see it
// immediately).
// Compared to the original game, we will solve a simplified problem here: You are given a set of nodes
// (cities) and a set of edges (road segments) of length 1 connecting the nodes.
// The longest road is defined as the longest path within the network that doesn’t use an edge twice.
// Nodes may be visited more than once, though.
// Input
// The input file will contain one or more test cases.
// The first line of each test case contains two integers: the number of nodes n (2 ≤ n ≤ 25) and the
// number of edges m (1 ≤ m ≤ 25). The next m lines describe the m edges. Each edge is given by the
// numbers of the two nodes connected by it. Nodes are numbered from 0 to n − 1. Edges are undirected.
// Nodes have degrees of three or less. The network is not neccessarily connected.
// Input will be terminated by two values of 0 for n and m.
// Output
// For each test case, print the length of the longest road on a single line.
// Sample Input
// 3 2
// 0 1
// 1 2
// 15 16
// 0 2
// 1 2
// 2 3
// 3 4
// 3 5
// 4 6
// 5 7
// 6 8
// 7 8
// 7 9
// 8 10
// 9 11
// 10 12
// 11 12
// 10 13
// 12 14
// 0 0
// Sample Output
// 2
// 12
import java.io.*;
/**
* Created by kdn251 on 2/20/17.
*/
public class TheSettlersOfCatan {
public static int[][] matrix = new int[30][30];
public static int answer;
public static void main(String args[]) throws Exception {
//initialize buffered reader
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line;
//iterate while current line is not equal to 0 0
while(!(line = br.readLine()).equals("0 0")) {
//initialize number of nodes and edges
int nodes = Integer.parseInt(line.split(" ")[0]);
int edges = Integer.parseInt(line.split(" ")[1]);
//iterate through all edges
for(int i = 0; i < edges; i++) {
//get edge between node x and node y
String[] current = br.readLine().split(" ");
int x = Integer.parseInt(current[0]);
int y = Integer.parseInt(current[1]);
//mark edge
matrix[x][y] = 1;
matrix[y][x] = 1;
}
//initialize answer to zero
answer = 0;
//dfs on every node
for(int i = 0; i < nodes; i++) {
dfs(i, 0, nodes);
}
//print answer
System.out.println(answer);
//reset graph
matrix = new int[30][30];
}
}
public static void dfs(int nd, int l, int nodes) {
//update answer if l is larger than current answer
if(l > answer) {
answer = l;
}
for(int i = 0; i < nodes; i++) {
if(matrix[nd][i] > 0) {
//ensure that edge is not counted twice (like marking as "visited")
matrix[nd][i] = 0;
matrix[i][nd] = 0;
//continue traversing graph and add 1 to count
dfs(i, l + 1, nodes);
//set current edge again in case node further into graph can reach it
matrix[nd][i] = 1;
matrix[i][nd] = 1;
}
}
}
}
//source: https://github.com/morris821028/UVa/blob/master/volume005/539%20-%20The%20Settlers%20of%20Catan.cpp
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/uva/ICanGuessTheDataStructure.java | uva/ICanGuessTheDataStructure.java | // There is a bag-like data structure, supporting two operations:
// 1 x Throw an element x into the bag.
// 2 Take out an element from the bag.
// Given a sequence of operations with return values, you’re going to guess the data structure. It is
// a stack (Last-In, First-Out), a queue (First-In, First-Out), a priority-queue (Always take out larger
// elements first) or something else that you can hardly imagine!
// Input:
// There are several test cases. Each test case begins with a line containing a single integer n (1 ≤ n ≤
// 1000). Each of the next n lines is either a type-1 command, or an integer 2 followed by an integer x.
// That means after executing a type-2 command, we get an element x without error. The value of x
// is always a positive integer not larger than 100. The input is terminated by end-of-file (EOF).
// Output:
// For each test case, output one of the following:
// stack It’s definitely a stack.
// queue It’s definitely a queue.
// priority queue It’s definitely a priority queue.
// impossible It can’t be a stack, a queue or a priority queue.
// not sure It can be more than one of the three data structures mentioned
// above.
// Sample Input
// 6
// 1 1
// 1 2
// 1 3
// 2 1
// 2 2
// 2 3
// 6
// 1 1
// 1 2
// 1 3
// 2 3
// 2 2
// 2 1
// 2
// 1 1
// 2 2
// 4
// 1 2
// 1 1
// 2 1
// 2 2
// 7
// 1 2
// 1 5
// 1 1
// 1 3
// 2 5
// 1 4
// 2 4
// Sample Output
// queue
// not sure
// impossible
// stack
// priority queue
/**
* Created by kdn251 on 2/10/17.
*/
import java.util.*;
import java.io.*;
public class ICanGuessTheDataStructure {
public static void main(String args[]) throws Exception {
//initialize data structures
Stack<Integer> stack = new Stack<Integer>();
Queue<Integer> queue = new LinkedList<Integer>();
//initialize max priority queue
PriorityQueue<Integer> priorityQueue = new PriorityQueue<Integer>(Collections.reverseOrder());
//initialize buffered reader
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line;
//iterate through all test cases
while ((line = br.readLine()) != null) {
//initialize removals for each data structure
int stackRemovals = 0;
int queueRemovals = 0;
int priorityQueueRemovals = 0;
int totalRemovals = 0;
//get number of test cases
int numberOfCases = Integer.parseInt(line);
//clear contents of data structures
queue.clear();
priorityQueue.clear();
stack.clear();
//iterate over all test cases
for (int i = 0; i < numberOfCases; i++) {
String[] currentLineSplit = br.readLine().split(" ");
int command = Integer.parseInt(currentLineSplit[0]);
int number = Integer.parseInt(currentLineSplit[1]);
//if command is 1, push number into all data structures
if (command == 1) {
stack.push(number);
queue.add(number);
priorityQueue.add(number);
} else {
//check which data structure to remove from and increment its removal count
if (!stack.isEmpty() && stack.peek() == number && stackRemovals == totalRemovals) {
stackRemovals++;
stack.pop();
}
if (!queue.isEmpty() && queue.peek() == number && queueRemovals == totalRemovals) {
queueRemovals++;
queue.remove();
}
if (!priorityQueue.isEmpty() && priorityQueue.peek() == number && priorityQueueRemovals == totalRemovals) {
priorityQueueRemovals++;
priorityQueue.remove();
}
totalRemovals++;
}
}
//check all removal counts for each data structure vs. total removal count and print the appropriate data structure
if ((stackRemovals == totalRemovals && queueRemovals == totalRemovals) || (stackRemovals == totalRemovals && stackRemovals == priorityQueueRemovals) || (queueRemovals == totalRemovals && priorityQueueRemovals == totalRemovals)) {
System.out.println("not sure");
} else if (stackRemovals == totalRemovals) {
System.out.println("stack");
} else if (queueRemovals == totalRemovals) {
System.out.println("queue");
} else if (priorityQueueRemovals == totalRemovals) {
System.out.println("priority queue");
} else {
System.out.println("impossible");
}
}
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/uva/PeskyPalindromes.java | uva/PeskyPalindromes.java | // A palindrome is a sequence of one or more characters that reads the same from the left as it does from
// the right. For example, Z, TOT and MADAM are palindromes, but ADAM is not.
// Your job, should you choose to accept it, is to write a program that reads a sequence of strings and
// for each string determines the number of UNIQUE palindromes that are substrings.
// Input
// The input file consists of a number of strings (one per line), of at most 80 characters each, starting in
// column 1.
// Output
// For each non-empty input line, the output consists of one line containing the message:
// The string 'input string' contains nnnn palindromes.
// where input string is replaced by the actual input string and nnnn is replaced by the number of
// UNIQUE palindromes that are substrings.
// Note:
// See below the explanation of the sample below
// • The 3 unique palindromes in ‘boy’ are ‘b’, ‘o’ and ‘y’.
// • The 4 unique palindromes in ‘adam’ are ‘a’, ‘d’, ‘m’, and ‘ada’.
// • The 5 unique palindromes in ‘madam’ are ‘m’, ‘a’, ‘d’, ‘ada’, and ‘madam’.
// • The 3 unique palindromes in ‘tot’ are ‘t’, ‘o’ and ‘tot’.
// Sample input
// boy
// adam
// madam
// tot
// Sample output
// The string 'boy' contains 3 palindromes.
// The string 'adam' contains 4 palindromes.
// The string 'madam' contains 5 palindromes.
// The string 'tot' contains 3 palindromes.
import java.util.*;
public class PeskyPalindromes {
public static void main(String args[]) {
int x;
Scanner sc = new Scanner(System.in);
while(sc.hasNext()) {
String currentString = sc.next();
List<String> allSubstrings = generateSubstrings(currentString);
int uniquePalindromes = findUniquePalindromes(allSubstrings);
System.out.println("The string " + "'" + currentString + "'" + " contains " + uniquePalindromes + " palindromes.");
}
}
public static List<String> generateSubstrings(String s) {
List<String> allSubstrings = new ArrayList<String>();
for(int i = 0; i < s.length(); i++) {
for(int j = i + 1; j <= s.length(); j++) {
String currentSubstring = s.substring(i, j);
if(!allSubstrings.contains(currentSubstring)) {
allSubstrings.add(currentSubstring);
}
}
}
return allSubstrings;
}
public static int findUniquePalindromes(List<String> allSubstrings) {
int totalUniquePalindromes = 0;
for(String s : allSubstrings) {
int left = 0;
int right = s.length() - 1;
boolean isPalindrome = true;
while(left < right) {
if(s.charAt(left) != s.charAt(right)) {
isPalindrome = false;
break;
}
left++;
right--;
}
if(isPalindrome) {
totalUniquePalindromes++;
}
}
return totalUniquePalindromes;
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/uva/LargestPrimeDivisor.java | uva/LargestPrimeDivisor.java | /**
* All integer numbers are divisible by primes. If a number is divisible by more than one prime number,
* then it obviously has a largest prime divisor. The numbers which do not fall in this category do not
* have a largest prime divisor. Given a number N your job is to write a program that finds its largest
* prime divisor. An integer number n is divisible by another integer number m if there is an integer t
* such that mt = n.
* Input
* The input file contains at most 450 sets of inputs. Each line contains a decimal integer N. N does
* not have more than 14 digits. Input is terminated by a line containing a single zero. So no other line
* except the last line contains a zero in the input. This line need not be processed.
* Output
* For each line of the input produce one line of output. This line contains an integer LPD, which is the
* largest prime divisor of the input number N. If the input number is not divisible by more than one
* prime number output a ‘-1’.
* Sample Input
* 2
* 6
* 100
* 0
* Sample Output
* -1
* 3
* 5
*/
//https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=2461
import java.util.Scanner;
public class LargestPrimeDivisor {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
long number = input.nextLong();
while (number != 0) {
number = (long) (Math.abs(number));
long largestPrimeDivisor = -1;
int numberOfPrimeDivisors = 0;
int sqrtOfNumber = (int) (Math.sqrt(number));
for (int i = 2; i <= sqrtOfNumber; i++) {
if (number % i == 0) {
numberOfPrimeDivisors++;
largestPrimeDivisor = i;
while (number % i == 0) {
number = number / i;
}
}
}
if (largestPrimeDivisor != -1 && number != 1) {
System.out.println(number);
} else if (numberOfPrimeDivisors <= 1) {
System.out.println(-1);
} else {
System.out.println(largestPrimeDivisor);
}
number = input.nextLong();
}
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/uva/BasicRemains.java | uva/BasicRemains.java |
/**
* Given a base b and two non-negative base b integers
* p and m, compute p mod m and print the
* result as a base-b integer. p mod m is defined
* as the smallest non-negative integer k such that
* p = a ∗ m + k for some integer a.
* Input
* Input consists of a number of cases. Each case is
* represented by a line containing three unsigned
* integers. The first, b, is a decimal number between
* 2 and 10. The second, p, contains up to 1000 digits between 0 and b − 1. The third, m, contains
* up to 9 digits between 0 and b − 1. The last case is followed by a line containing ‘0’.
* Output
* For each test case, print a line giving p mod m as a base-b integer.
* Sample Input
* 2 1100 101
* 10 123456789123456789123456789 1000
* 0
* Sample Output
* 10
* 789
*
*/
//https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1492
import java.math.BigInteger;
import java.util.Scanner;
public class BasicRemains {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (input.hasNext()) {
int baseNumber = input.nextInt();
if (baseNumber == 0) {
break;
}
BigInteger p = new BigInteger(input.next(), baseNumber);
BigInteger m = new BigInteger(input.next(), baseNumber);
System.out.println((p.mod(m)).toString(baseNumber));
}
}
} | java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/uva/AverageSpeed.java | uva/AverageSpeed.java | /**
* You have bought a car in order to drive from Waterloo to a big city. The odometer on their car is
* broken, so you cannot measure distance. But the speedometer and cruise control both work, so the car
* can maintain a constant speed which can be adjusted from time to time in response to speed limits,
* traffic jams, and border queues. You have a stopwatch and note the elapsed time every time the speed
* changes. From time to time you wonder, “how far have I come?”. To solve this problem you must write
* a program to run on your laptop computer in the passenger seat.
* Input
* Standard input contains several lines of input: Each speed change is indicated by a line specifying the
* elapsed time since the beginning of the trip (hh:mm:ss), followed by the new speed in km/h. Each
* query is indicated by a line containing the elapsed time. At the outset of the trip the car is stationary.
* Elapsed times are given in non-decreasing order and there is at most one speed change at any given
* time.
* Output
* For each query in standard input, you should print a line giving the time and the distance travelled, in
* the format below.
* Sample Input
* 00:00:01 100
* 00:15:01
* 00:30:01
* 01:00:01 50
* 03:00:01
* 03:00:05 140
* Sample Output
* 00:15:01 25.00 km
* 00:30:01 50.00 km
* 03:00:01 200.00 km
*/
//https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1222
import java.text.DecimalFormat;
import java.util.Scanner;
public class AverageSpeed {
public static void main(String[] args) {
int speed = 0;
boolean reachedTheEnd = false;
Scanner input = new Scanner(System.in);
String nextLine = input.nextLine();
double hour = 0;
double baseHour = 0;
double kilometersPassed = 0;
while (!reachedTheEnd) {
String[] time1 = nextLine.split(" ");
String[] time = nextLine.split(":");
String[] extendedTime = new String[2];
DecimalFormat formatter = new DecimalFormat("#0.00");
hour = calcHours(time1[0]);
kilometersPassed += (hour - baseHour) * speed;
if (time[2].contains(" ")) {
extendedTime = time[2].split(" ");
speed = Integer.valueOf(extendedTime[1]);
} else {
System.out.print(nextLine + " "
+ formatter.format(kilometersPassed) + " km\n");
}
baseHour = hour;
nextLine = input.nextLine();
}
}
private static double calcHours(String s) {
String[] arr = s.split(":");
return (Integer.parseInt(arr[0]) * 3600 + Integer.parseInt(arr[1]) * 60 + Integer
.parseInt(arr[2])) * 1.0 / 3600;
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/uva/AddingReversedNumbers.java | uva/AddingReversedNumbers.java | /**
* The Antique Comedians of Malidinesia prefer comedies to tragedies. Unfortunately, most of the ancient
* plays are tragedies. Therefore the dramatic advisor of ACM has decided to transfigure some tragedies
* into comedies. Obviously, this work is very hard because the basic sense of the play must be kept intact,
* although all the things change to their opposites. For example the numbers: if any number appears in
* the tragedy, it must be converted to its reversed form before being accepted into the comedy play.
* Reversed number is a number written in arabic numerals but the order of digits is reversed. The
* first digit becomes last and vice versa. For example, if the main hero had 1245 strawberries in the
* tragedy, he has 5421 of them now. Note that all the leading zeros are omitted. That means if the
* number ends with a zero, the zero is lost by reversing (e.g. 1200 gives 21). Also note that the reversed
* number never has any trailing zeros.
* ACM needs to calculate with reversed numbers. Your task is to add two reversed numbers and
* output their reversed sum. Of course, the result is not unique because any particular number is a
* reversed form of several numbers (e.g. 21 could be 12, 120 or 1200 before reversing). Thus we must
* assume that no zeros were lost by reversing (e.g. assume that the original number was 12).
* Input
* The input consists of N cases. The first line of the input contains only positive integer N. Then follow
* the cases. Each case consists of exactly one line with two positive integers separated by space. These
* are the reversed numbers you are to add. Numbers will be at most 200 characters long.
* Output
* For each case, print exactly one line containing only one integer — the reversed sum of two reversed
* numbers. Omit any leading zeros in the output.
* Sample Input
* 3
* 24 1
* 4358 754
* 305 794
* Sample Output
* 34
* 1998
* 1
*/
//https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=654
import java.math.BigInteger;
import java.util.Scanner;
public class AddingReversedNumbers {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int numberOfTestCases = input.nextInt();
while (numberOfTestCases != 0) {
BigInteger first = input.nextBigInteger();
BigInteger second = input.nextBigInteger();
StringBuilder firstString = new StringBuilder(first + "");
StringBuilder secondString = new StringBuilder(second + "");
BigInteger firstReversed = new BigInteger(firstString.reverse()
.toString());
BigInteger secondReversed = new BigInteger(secondString.reverse()
.toString());
BigInteger result = firstReversed.add(secondReversed);
String resultReversed = new StringBuilder(result + "").reverse()
.toString();
System.out.println(resultReversed.replaceFirst("^0*", ""));
numberOfTestCases--;
}
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/uva/TheLastNonZeroDigit.java | uva/TheLastNonZeroDigit.java |
/**
* In this problem you will be given two decimal integer number N, M. You will have to find the last
* non-zero digit of the P
* N
* M . This means no of permutations of N things taking M at a time.
* Input
* The input file contains several lines of input. Each line of the input file contains two integers N
* (0 ≤ N ≤ 20000000), M (0 ≤ M ≤ N). Input is terminated by end-of-file.
* Output
* For each line of the input file you should output a single digit, which is the last non-zero digit of P
* N
* M .
* For example, if P
* N
* M is 720 then the last non-zero digit is 2. So in this case your output should be 2.
* Sample Input
* 10 10
* 10 5
* 25 6
* Sample Output
* 8
* 4
* 2
*/
//https://uva.onlinejudge.org/index.php?option=onlinejudge&page=show_problem&problem=1153
import java.util.Scanner;
public class TheLastNonZeroDigit {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (input.hasNext()) {
long n = input.nextInt();
long m = input.nextInt();
long product = 1;
for (long i = (n - m + 1); i < n + 1; i++) {
product = product * i;
while (product % 10 == 0) {
product = product / 10;
}
product = product % (long) (Math.pow(10, 11));
}
String number = product + "";
for (int i = number.length() - 1; i > -1; i--) {
char c = number.charAt(i);
if (c != '0') {
System.out.println(c);
break;
}
}
}
}
} | java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/uva/IntegerInquiry.java | uva/IntegerInquiry.java | /**
* One of the first users of BIT’s new supercomputer was Chip Diller. He extended his exploration of
* powers of 3 to go from 0 to 333 and he explored taking various sums of those numbers.
* “This supercomputer is great,” remarked Chip. “I only wish Timothy were here to see these results.”
* (Chip moved to a new apartment, once one became available on the third floor of the Lemon Sky
* apartments on Third Street.)
* Input
* The input will consist of at most 100 lines of text, each of which contains a single VeryLongInteger.
* Each VeryLongInteger will be 100 or fewer characters in length, and will only contain digits (no
* VeryLongInteger will be negative).
* The final input line will contain a single zero on a line by itself.
* Output
* Your program should output the sum of the VeryLongIntegers given in the input.
* Sample Input
* 123456789012345678901234567890
* 123456789012345678901234567890
* 123456789012345678901234567890
* 0
* Sample Output
* 370370367037037036703703703670
*/
//https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&category=&problem=365
import java.math.BigInteger;
import java.util.Scanner;
public class IntegerInquiry {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
BigInteger sum = BigInteger.ZERO;
while (true) {
BigInteger number = input.nextBigInteger();
if (number.equals(BigInteger.ZERO)) {
break;
}
sum = sum.add(number);
}
System.out.println(sum);
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/uva/BackToIntermediateMath.java | uva/BackToIntermediateMath.java | /**
* Umm! So, you claim yourself as an intelligent one? Let me check. As, computer science students always
* insist on optimization whenever possible, I give you an elementary problem of math to optimize.
* You are trying to cross a river of width d meters. You are given that, the river flows at v ms−1 and
* you know that you can speed up the boat in u ms−1
* . There may be two goals how to cross the river:
* One goal (called fastest path) is to cross it in fastest time, and it does not matter how far the flow of
* the river takes the boat. The other goal (called shortest path) is to steer the boat in a direction so that
* the flow of the river doesn’t take the boat away, and the boat passes the river in a line perpendicular to
* the boarder of the river. Is it always possible to have two different paths, one to pass at shortest time
* and the other at shortest path? If possible then, what is the difference (Let P s) between the times
* needed to cross the river in the different ways?
* Input
* The first line in the input file is an integer representing the number of test cases. Each of the test cases
* follows below. Each case consists three real numbers (all are nonnegative, d is positive) denoting the
* value of d, v and u respectively.
* Output
* For each test case, first print the serial number of the case, a colon, an space and then print ‘can’t
* determine’ (without the quotes) if it is not possible to find different paths as stated above, else print
* the value of P corrected to three digits after decimal point. Check the sample input & output.
* Sample Input
* 3
* 8 5 6
* 1 2 3
* 1 5 6
* Sample Output
* Case 1: 1.079
* Case 2: 0.114
* Case 3: 0.135
*/
//https://uva.onlinejudge.org/index.php?option=onlinejudge&Itemid=99999999&page=show_problem&category=&problem=1714
import java.text.DecimalFormat;
import java.util.Scanner;
public class BackToIntermediateMath {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int numberOfTestCases = input.nextInt();
DecimalFormat formatter = new DecimalFormat("#0.000");
for (int i = 0; i < numberOfTestCases; i++) {
double distance = input.nextDouble();
double riverSpeed = input.nextDouble();
double boatSpeed = input.nextDouble();
if (riverSpeed == 0 || boatSpeed == 0 || boatSpeed <= riverSpeed) {
System.out.println("Case " + (i + 1) + ": can't determine");
} else {
double P1 = distance / boatSpeed;
double P2 = distance
/ Math.sqrt(boatSpeed * boatSpeed - riverSpeed
* riverSpeed);
System.out.print("Case " + (i + 1) + ": "
+ formatter.format(Math.abs(P1 - P2)) + "\n");
}
}
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/uva/HighPrecisionNumber.java | uva/HighPrecisionNumber.java |
/**
* A number with 30 decimal digits of precision can be represented by a structure type as shown in the
* examples below. It includes a 30-element integer array (digits), a single integer (decpt) to represent
* the position of the decimal point and an integer (or character) to represent the sign (+/-).
* Your task is to write a program to calculate the sum of high-precision numbers.
* Input
* The first line contains a positive integer n (1 ≤ n ≤ 100) indicating the number of groups of highprecision
* numbers (maximum 30 significant digits). Each group includes high-precision numbers (one
* number in a line) and a line with only 0 indicating the end of each group. A group can contain 100
* numbers at most.
* Output
* For each group, print out the sum of high-precision numbers (one value in a line). All zeros after the
* decimal point located behind the last non-zero digit must be discarded
*
* Sample Input
* 4
* 4.12345678900000000005
* -0.00000000012
* 0
* -1300.1
* 1300.123456789
* 0.0000000012345678912345
* 0
* 1500.61345975
* -202.004285
* -8.60917475
* 0
* -218.302869584
* 200.0000123456789
* 0
*
* Sample Output
* 4.12345678888000000005
* 0.0234567902345678912345
* 1290
* -18.3028572383211
*/
//https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=2921
import java.math.BigDecimal;
import java.util.Scanner;
public class HighPrecisionNumber {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int numberOfGroups = input.nextInt();
while (numberOfGroups != 0) {
BigDecimal sum = BigDecimal.ZERO;
BigDecimal number = input.nextBigDecimal();
while (!number.equals(BigDecimal.ZERO)) {
sum = sum.add(number);
number = input.nextBigDecimal();
}
System.out.println(sum.toPlainString().replaceFirst(
"\\.0*$|(\\.\\d*?)0+$", "$1"));
numberOfGroups--;
}
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/uva/DigitCounting.java | uva/DigitCounting.java | /**
* Trung is bored with his mathematics homeworks. He takes a piece of chalk and starts writing a sequence
* of consecutive integers starting with 1 to N (1 < N < 10000). After that, he counts the number of
* times each digit (0 to 9) appears in the sequence. For example, with N = 13, the sequence is:
* 12345678910111213
* In this sequence, 0 appears once, 1 appears 6 times, 2 appears 2 times, 3 appears 3 times, and each
* digit from 4 to 9 appears once. After playing for a while, Trung gets bored again. He now wants to
* write a program to do this for him. Your task is to help him with writing this program.
* Input
* The input file consists of several data sets. The first line of the input file contains the number of data
* sets which is a positive integer and is not bigger than 20. The following lines describe the data sets.
* For each test case, there is one single line containing the number N.
* Output
* For each test case, write sequentially in one line the number of digit 0, 1, . . . 9 separated by a space.
* Sample Input
* 2
* 3
* 13
* Sample Output
* 0 1 1 1 0 0 0 0 0 0
* 1 6 2 2 1 1 1 1 1 1
*/
//https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=3666
import static java.lang.Integer.parseInt;
import static java.lang.System.exit;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.StringTokenizer;
public class DigitCounting {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int numberOfTestCases = input.nextInt();
while (numberOfTestCases != 0) {
int[] numbers = new int[10];
int number = input.nextInt();
for (int i = number; i > 0; i--) {
int j = i;
while (j != 0) {
numbers[j % 10]++;
j = j / 10;
}
}
for (int i = 0; i < 10; i++) {
if (i != 0) {
System.out.print(" ");
}
System.out.print(numbers[i]);
}
System.out.println();
numberOfTestCases--;
}
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.