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/facebook/ValidParentheses.java
company/facebook/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/facebook/RemoveDuplicatesFromSortedArray.java
company/facebook/RemoveDuplicatesFromSortedArray.java
// Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length. // Do not allocate extra space for another array, you must do this in place with constant memory. // For example, // Given input array nums = [1,1,2], // Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn't matter what you leave beyond the new length. public class RemoveDuplicatesFromSortedArray { public int removeDuplicates(int[] nums) { if(nums.length == 0 || nums == null) { return 0; } if(nums.length < 2) { return nums.length; } int index = 1; for(int i = 1; i < nums.length; i++) { if(nums[i] != nums[i - 1]) { nums[index++] = nums[i]; } } return index; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/facebook/WallsAndGates.java
company/facebook/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/facebook/RomanToInteger.java
company/facebook/RomanToInteger.java
// Given a roman numeral, convert it to an integer. // Input is guaranteed to be within the range from 1 to 3999 public class RomanToInteger { public int romanToInt(String s) { HashMap<Character, Integer> map = new HashMap<Character, Integer>(); map.put('I', 1); map.put('V', 5); map.put('X', 10); map.put('L', 50); map.put('C', 100); map.put('D', 500); map.put('M', 1000); int total = 0; for(int i = 0; i < s.length() - 1; i++) { if(map.get(s.charAt(i)) < map.get(s.charAt(i + 1))) { total -= map.get(s.charAt(i)); } else { total += map.get(s.charAt(i)); } } total += map.get(s.charAt(s.length() - 1)); return total; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/facebook/BinarySearchTreeIterator.java
company/facebook/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/facebook/SortColors.java
company/facebook/SortColors.java
// Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue. // Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. // Note: // You are not suppose to use the library's sort function for this problem. public class SortColors { public void sortColors(int[] nums) { int wall = 0; for(int i = 0; i < nums.length; i++) { if(nums[i] < 1) { int temp = nums[i]; nums[i] = nums[wall]; nums[wall] = temp; wall++; } } for(int i = 0; i < nums.length; i++) { if(nums[i] == 1) { int temp = nums[i]; nums[i] = nums[wall]; nums[wall] = temp; wall++; } } } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/facebook/FirstBadVersion.java
company/facebook/FirstBadVersion.java
// You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad. // Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following ones to be bad. // You are given an API bool isBadVersion(version) which will return whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API. /* The isBadVersion API is defined in the parent class VersionControl. boolean isBadVersion(int version); */ public class FirstBadVersion extends VersionControl { public int firstBadVersion(int n) { int start = 1; int end = n; while(start < end) { int mid = start + (end - start) / 2; if(!isBadVersion(mid)) { start = mid + 1; } else { end = mid; } } return start; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/facebook/ProductOfArrayExceptSelf.java
company/facebook/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/facebook/MinimumWindowSubstring.java
company/facebook/MinimumWindowSubstring.java
// Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n). // For example, // S = "ADOBECODEBANC" // T = "ABC" // Minimum window is "BANC". // Note: // If there is no such window in S that covers all characters in T, return the empty string "". // If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S. public class MinimumWindowSubstring { public String minWindow(String s, String t) { HashMap<Character, Integer> map = new HashMap<>(); for(char c : s.toCharArray()) { map.put(c, 0); } for(char c : t.toCharArray()) { if(map.containsKey(c)) { map.put(c, map.get(c)+ 1); } else { return ""; } } int start = 0; int end = 0; int minStart = 0; int minLength = Integer.MAX_VALUE; int counter = t.length(); while(end < s.length()) { char c1 = s.charAt(end); if(map.get(c1) > 0) { counter--; } map.put(c1, map.get(c1) - 1); end++; while(counter == 0) { if(minLength > end - start) { minLength = end - start; minStart = start; } char c2 = s.charAt(start); map.put(c2, map.get(c2) + 1); if(map.get(c2) > 0) { counter++; } start++; } } return minLength == Integer.MAX_VALUE ? "" : s.substring(minStart, minStart + minLength); } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/facebook/BinaryTreePaths.java
company/facebook/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/facebook/GroupAnagrams.java
company/facebook/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/facebook/Subsets.java
company/facebook/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/facebook/MeetingRooms.java
company/facebook/MeetingRooms.java
// Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei), determine if a person could attend all meetings. // For example, // Given [[0, 30],[5, 10],[15, 20]], // return false. /** * 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 MeetingRooms { public boolean canAttendMeetings(Interval[] intervals) { if(intervals == null) { return false; } // Sort the intervals by start time Arrays.sort(intervals, new Comparator<Interval>() { public int compare(Interval a, Interval b) { return a.start - b.start; } }); for(int i = 1; i < intervals.length; i++) { if(intervals[i].start < intervals[i - 1].end) { return false; } } return true; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/facebook/RemoveInvalidParentheses.java
company/facebook/RemoveInvalidParentheses.java
// Remove the minimum number of invalid parentheses in order to make the input string valid. Return all possible results. // Note: The input string may contain letters other than the parentheses ( and ). // Examples: // "()())()" -> ["()()()", "(())()"] // "(a)())()" -> ["(a)()()", "(a())()"] // ")(" -> [""] public class RemoveInvalidParentheses { public List<String> removeInvalidParentheses(String s) { List<String> result = new ArrayList<>(); remove(s, result, 0, 0, new char[]{'(', ')'}); return result; } public void remove(String s, List<String> result, int last_i, int last_j, char[] par) { for (int stack = 0, i = last_i; i < s.length(); i++) { if (s.charAt(i) == par[0]) { stack++; } if (s.charAt(i) == par[1]) { stack--; } if (stack >= 0) { continue; } for (int j = last_j; j <= i; j++) { if (s.charAt(j) == par[1] && (j == last_j || s.charAt(j - 1) != par[1])) { remove(s.substring(0, j) + s.substring(j + 1, s.length()), result, i, j, par); } } return; } String reversed = new StringBuilder(s).reverse().toString(); if (par[0] == '(') { // finished left to right remove(reversed, result, 0, 0, new char[]{')', '('}); } else { // finished right to left result.add(reversed); } } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/facebook/WordBreak.java
company/facebook/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/facebook/SubsetsII.java
company/facebook/SubsetsII.java
// Given a collection of integers that might contain duplicates, nums, return all possible subsets. // Note: The solution set must not contain duplicate subsets. // For example, // If nums = [1,2,2], a solution is: // [ // [2], // [1], // [1,2,2], // [2,2], // [1,2], // [] // ] public class SubsetsII { public List<List<Integer>> subsetsWithDup(int[] nums) { Arrays.sort(nums); List<List<Integer>> result = new ArrayList<List<Integer>>(); if(nums.length == 0 || nums == null) { return result; } helper(nums, new ArrayList<Integer>(), 0, result); return result; } public void helper(int[] nums, ArrayList<Integer> current, int index, List<List<Integer>> result) { result.add(current); for(int i = index; i < nums.length; i++) { if(i > index && nums[i] == nums[i - 1]) { continue; } ArrayList<Integer> newCurrent = new ArrayList<Integer>(current); newCurrent.add(nums[i]); helper(nums, newCurrent, i + 1, result); } } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/facebook/InsertInterval.java
company/facebook/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/facebook/PaintHouseII.java
company/facebook/PaintHouseII.java
// There are a row of n houses, each house can be painted with one of the k colors. The cost of painting each house with a certain color is different. You have to paint all the houses such that no two adjacent houses have the same color. // The cost of painting each house with a certain color is represented by a n x k cost matrix. For example, costs[0][0] is the cost of painting house 0 with color 0; costs[1][2] is the cost of painting house 1 with color 2, and so on... Find the minimum cost to paint all houses. // Note: // All costs are positive integers. // Follow up: // Could you solve it in O(nk) runtime? public class PaintHouseII { public int minCostII(int[][] costs) { if(costs == null|| costs.length == 0) { return 0; } int m = costs.length; int n = costs[0].length; int min1 = -1; int min2 = -1; for(int i = 0; i < m; i++) { int last1 = min1; int last2 = min2; min1 = -1; min2 = -1; for(int j = 0; j < n; j++) { if(j != last1) { costs[i][j] += last1 < 0 ? 0 : costs[i - 1][last1]; } else { costs[i][j] += last2 < 0 ? 0 : costs[i - 1][last2]; } if(min1 < 0 || costs[i][j] < costs[i][min1]) { min2 = min1; min1 = j; } else if(min2 < 0 || costs[i][j] < costs[i][min2]) { min2 = j; } } } return costs[m - 1][min1]; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/facebook/FlattenNestedListIterator.java
company/facebook/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/facebook/SparseMatrixMultiplication.java
company/facebook/SparseMatrixMultiplication.java
// Given two sparse matrices A and B, return the result of AB. // You may assume that A's column number is equal to B's row number. // Example: // A = [ // [ 1, 0, 0], // [-1, 0, 3] // ] // B = [ // [ 7, 0, 0 ], // [ 0, 0, 0 ], // [ 0, 0, 1 ] // ] // | 1 0 0 | | 7 0 0 | | 7 0 0 | // AB = | -1 0 3 | x | 0 0 0 | = | -7 0 3 | // | 0 0 1 | public class SparseMatrixMultiplication { public int[][] multiply(int[][] A, int[][] B) { int m = A.length; int n = A[0].length; int nB = B[0].length; int[][] C = new int[m][nB]; for(int i = 0; i < m; i++) { for(int j = 0; j < n; j++) { if(A[i][j] != 0) { for(int k = 0; k < nB; k++) { if(B[j][k] != 0) { C[i][k] += A[i][j] * B[j][k]; } } } } } return C; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/facebook/PalindromeLinkedList.java
company/facebook/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/facebook/ExclusiveTimeOfFunctions.java
company/facebook/ExclusiveTimeOfFunctions.java
//Given the running logs of n functions that are executed in a nonpreemptive single threaded CPU, find the exclusive time of these functions. //Each function has a unique id, start from 0 to n-1. A function may be called recursively or by another function. //A log is a string has this format : function_id:start_or_end:timestamp. For example, "0:start:0" means function 0 starts from the very beginning of time 0. "0:end:0" means function 0 ends to the very end of time 0. //Exclusive time of a function is defined as the time spent within this function, the time spent by calling other functions should not be considered as this function's exclusive time. You should return the exclusive time of each function sorted by their function id. //Example 1: //Input: //n = 2 //logs = //["0:start:0", //"1:start:2", //"1:end:5", //"0:end:6"] //Output:[3, 4] //Explanation: //Function 0 starts at time 0, then it executes 2 units of time and reaches the end of time 1. //Now function 0 calls function 1, function 1 starts at time 2, executes 4 units of time and end at time 5. //Function 0 is running again at time 6, and also end at the time 6, thus executes 1 unit of time. //So function 0 totally execute 2 + 1 = 3 units of time, and function 1 totally execute 4 units of time. //Note: //Input logs will be sorted by timestamp, NOT log id. //Your output should be sorted by function id, which means the 0th element of your output corresponds to the exclusive time of function 0. //Two functions won't start or end at the same time. //Functions could be called recursively, and will always end. //1 <= n <= 100 class ExclusiveTimeOfFunctions { public int[] exclusiveTime(int n, List<String> logs) { Stack<Integer> stack = new Stack <Integer>(); int[] result = new int[n]; String[] current = logs.get(0).split(":"); stack.push(Integer.parseInt(current[0])); int i = 1; int previous = Integer.parseInt(current[2]); while (i < logs.size()) { current = logs.get(i).split(":"); if (current[1].equals("start")) { if (!stack.isEmpty()) { result[stack.peek()] += Integer.parseInt(current[2]) - previous; } stack.push(Integer.parseInt(current[0])); previous = Integer.parseInt(current[2]); } else { result[stack.peek()] += Integer.parseInt(current[2]) - previous + 1; stack.pop(); previous = Integer.parseInt(current[2]) + 1; } i++; } return result; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/facebook/SquareRootX.java
company/facebook/SquareRootX.java
// Implement int sqrt(int x). // Compute and return the square root of x. public class SquareRootX { public int mySqrt(int x) { if(x == 0) { return 0; } int left = 1; int right = x; while(left <= right) { int mid = left + (right - left) / 2; if(mid == x / mid) { return mid; } else if(mid > x / mid) { right = mid - 1; } else if(mid < x / mid) { left = mid + 1; } } return right; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/facebook/CombinationSumIV.java
company/facebook/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 Solution { 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/facebook/LongestConsecutiveSequence.java
company/facebook/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/facebook/LowestCommonAncestorOfABinaryTree.java
company/facebook/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 LowestCommonAncestorsOfABinaryTree { 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/facebook/PowerOfXToTheN.java
company/facebook/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/facebook/AddBinary.java
company/facebook/AddBinary.java
// Given two binary strings, return their sum (also a binary string). // For example, // a = "11" // b = "1" // Return "100" public class AddBinary { public String addBinary(String a, String b) { StringBuilder result = new StringBuilder(); int carry = 0; int i = a.length() - 1; int j = b.length() - 1; while(i >= 0 || j >= 0) { int sum = carry; if(i >= 0) { sum += a.charAt(i--) - '0'; } if(j >= 0) { sum += b.charAt(j--) - '0'; } result.append(sum % 2); carry = sum / 2; } if(carry != 0) { result.append(carry); } return result.reverse().toString(); } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/facebook/SumOfLeftLeaves.java
company/facebook/SumOfLeftLeaves.java
// Find the sum of all left leaves in a given binary tree. // Example: // 3 // / \ // 9 20 // / \ // 15 7 // There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24. /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class SumOfLeftLeaves { public int sumOfLeftLeaves(TreeNode root) { if(root == null) { return 0; } int total = 0; if(root.left != null) { if(root.left.left == null && root.left.right == null) { total += root.left.val; } else { total += sumOfLeftLeaves(root.left); } } total += sumOfLeftLeaves(root.right); return total; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/facebook/BinaryTreeLevelOrderTraversal.java
company/facebook/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/facebook/WordSearch.java
company/facebook/WordSearch.java
// Given a 2D board and a word, find if the word exists in the grid. // The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once. // For example, // Given board = // [ // ['A','B','C','E'], // ['S','F','C','S'], // ['A','D','E','E'] // ] // word = "ABCCED", -> returns true, // word = "SEE", -> returns true, // word = "ABCB", -> returns false. public class WordSearch { public boolean exist(char[][] board, String word) { char[] w = word.toCharArray(); for(int i = 0; i < board.length; i++) { for(int j = 0; j < board[0].length; j++) { if(search(board, i, j, w, 0)) { return true; } } } return false; } public boolean search(char[][] board, int i, int j, char[] w, int index) { if(index == w.length) { return true; } if(i < 0 || i >= board.length || j < 0 || j >= board[0].length) { return false; } if(board[i][j] != w[index]) { return false; } board[i][j] ^= 256; boolean exist = search(board, i + 1, j, w, index + 1) || search(board, i - 1, j, w, index + 1) || search(board, i, j + 1, w, index + 1) || search(board, i, j - 1, w, index + 1); board[i][j] ^= 256; return exist; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/facebook/SearchInRotatedSortedArray.java
company/facebook/SearchInRotatedSortedArray.java
// Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. // (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). // You are given a target value to search. If found in the array return its index, otherwise return -1. // You may assume no duplicate exists in the array. public class SearchInRotatedSortedArray { public int search(int[] nums, int target) { int left = 0; int right = nums.length - 1; while(left <= right) { int mid = left + (right - left) / 2; if(nums[mid] == target) { return mid; } if(nums[left] <= nums[mid]) { if(target < nums[mid] && target >= nums[left]) { right = mid - 1; } else { left = mid + 1; } } if(nums[mid] <= nums[right]) { if(target > nums[mid] && target <= nums[right]) { left = mid + 1; } else { right = mid - 1; } } } return -1; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/facebook/ValidateBinarySearchTree.java
company/facebook/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/company/facebook/ValidPalindrome.java
company/facebook/ValidPalindrome.java
public class ValidPalindrome { public boolean isPalindrome(String s) { int left = 0; int right = s.length() - 1; while(left < right) { while(!Character.isLetterOrDigit(s.charAt(left)) && left < right) { left++; } while(!Character.isLetterOrDigit(s.charAt(right)) && right > left) { right--; } if(Character.toLowerCase(s.charAt(left)) != Character.toLowerCase(s.charAt(right))) { return false; } left++; right--; } return true; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/airbnb/MergeKSortedLists.java
company/airbnb/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/airbnb/TwoSum.java
company/airbnb/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/airbnb/AddTwoNumbers.java
company/airbnb/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/airbnb/ContainsDuplicatesII.java
company/airbnb/ContainsDuplicatesII.java
//Given an array of integers and an integer k, find out whether there are two distinct indices i and //j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k. class ContainsDuplicatesII { public boolean containsNearbyDuplicate(int[] nums, int k) { HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); for(int i = 0; i < nums.length; i++) { int current = nums[i]; if(map.containsKey(current) && i - map.get(current) <= k) { return true; } else { map.put(current, i); } } return false; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/airbnb/RegularExpressionMatching.java
company/airbnb/RegularExpressionMatching.java
// Implement regular expression matching with support for '.' and '*'. // '.' Matches any single character. // '*' Matches zero or more of the preceding element. // The matching should cover the entire input string (not partial). // The function prototype should be: // bool isMatch(const char *s, const char *p) // Some examples: // isMatch("aa","a") → false // isMatch("aa","aa") → true // isMatch("aaa","aa") → false // isMatch("aa", "a*") → true // isMatch("aa", ".*") → true // isMatch("ab", ".*") → true // isMatch("aab", "c*a*b") → true public class RegularExpressionMatching { public boolean isMatch(String s, String p) { if(s == null || p == null) { return false; } boolean[][] dp = new boolean[s.length() + 1][p.length() + 1]; dp[0][0] = true; for(int i = 0; i < p.length(); i++) { if(p.charAt(i) == '*' && dp[0][i - 1]) { dp[0][i + 1] = true; } } for(int i = 0; i < s.length(); i++) { for(int j = 0; j < p.length(); j++) { if(p.charAt(j) == '.') { dp[i + 1][j + 1] = dp[i][j]; } if(p.charAt(j) == s.charAt(i)) { dp[i + 1][j + 1] = dp[i][j]; } if(p.charAt(j) == '*') { if(p.charAt(j - 1) != s.charAt(i) && p.charAt(j - 1) != '.') { dp[i + 1][j + 1] = dp[i + 1][j - 1]; } else { dp[i + 1][j + 1] = (dp[i + 1][j] || dp[i][j + 1] || dp[i + 1][j - 1]); } } } } return dp[s.length()][p.length()]; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/airbnb/ValidParentheses.java
company/airbnb/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/airbnb/ConvertSortedArrayToBinarySearchTree.java
company/airbnb/ConvertSortedArrayToBinarySearchTree.java
// Given an array where elements are sorted in ascending order, convert it to a height balanced BST. /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public TreeNode sortedArrayToBST(int[] nums) { if(nums.length == 0) { return null; } TreeNode root = helper(nums, 0, nums.length - 1); return root; } private TreeNode helper(int[] nums, int start, int end) { if(start <= end) { int mid = (start + end) / 2; TreeNode current = new TreeNode(nums[mid]); current.left = helper(nums, start, mid - 1); current.right = helper(nums, mid + 1, end); return current; } return null; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/airbnb/HouseRobber.java
company/airbnb/HouseRobber.java
// You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night. // Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police. public class HouseRobber { public int rob(int[] nums) { if(nums.length == 0) { return 0; } if(nums.length == 1) { return nums[0]; } int[] dp = new int[nums.length]; dp[0] = nums[0]; dp[1] = nums[0] > nums[1] ? nums[0] : nums[1]; for(int i = 2; i < nums.length; i++) { dp[i] = Math.max(dp[i - 2] + nums[i], dp[i - 1]); } return dp[dp.length - 1]; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/airbnb/ContainsDuplicate.java
company/airbnb/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/bloomberg/LinkedListCycle.java
company/bloomberg/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/bloomberg/FirstUniqueCharacterInAString.java
company/bloomberg/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/bloomberg/ReverseWordsInAString.java
company/bloomberg/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/bloomberg/UniquePaths.java
company/bloomberg/UniquePaths.java
//A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). // //The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). // //How many possible unique paths are there? class UniquePaths { public int uniquePaths(int m, int n) { Integer[][] map = new Integer[m][n]; //only 1 way to get to ith row, 0th column (move down) for(int i = 0; i < m; i++){ map[i][0] = 1; } //only 1 way to get to ith column, 0th row (move right) for(int j= 0; j < n; j++){ map[0][j]=1; } //x ways to get to ith row, jth column (# of ways to get to //ith - 1 row, jth column + # of ways to get to jth - 1 column //ith column for(int i = 1;i < m; i++){ for(int j = 1; j < n; j++){ map[i][j] = map[i - 1][j] + map[i][j - 1]; } } return map[m - 1][n - 1]; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/bloomberg/MinStack.java
company/bloomberg/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/bloomberg/LongestPalindromicSubstring.java
company/bloomberg/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/uber/ReverseLinkedList.java
company/uber/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/uber/DecodeWays.java
company/uber/DecodeWays.java
// A message containing letters from A-Z is being encoded to numbers using the following mapping: // 'A' -> 1 // 'B' -> 2 // ... // 'Z' -> 26 // Given an encoded message containing digits, determine the total number of ways to decode it. // For example, // Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12). // The number of ways decoding "12" is 2. public class DecodeWays { public int numDecodings(String s) { int n = s.length(); if(n == 0) { return 0; } int[] dp = new int[n + 1]; dp[n] = 1; dp[n - 1] = s.charAt(n - 1) != '0' ? 1 : 0; for(int i = n - 2; i >= 0; i--) { if(s.charAt(i) == '0') { continue; } else { dp[i] = (Integer.parseInt(s.substring(i, i + 2)) <= 26) ? dp[i + 1] + dp[i + 2] : dp[i + 1]; } } return dp[0]; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/uber/MergeKSortedLists.java
company/uber/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/uber/EncodeAndDecodeTinyURL.java
company/uber/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/uber/OneEditDistance.java
company/uber/OneEditDistance.java
// Given two strings S and T, determine if they are both one edit distance apart. public class OneEditDistance { public boolean isOneEditDistance(String s, String t) { //iterate through the length of the smaller string for(int i = 0; i < Math.min(s.length(), t.length()); i++) { //if the current characters of the two strings are not equal if(s.charAt(i) != t.charAt(i)) { //return true if the remainder of the two strings are equal, false otherwise if(s.length() == t.length()) { return s.substring(i + 1).equals(t.substring(i + 1)); } else if(s.length() < t.length()) { //return true if the strings would be the same if you deleted a character from string t return s.substring(i).equals(t.substring(i + 1)); } else { //return true if the strings would be the same if you deleted a character from string s return t.substring(i).equals(s.substring(i + 1)); } } } //if all characters match for the length of the two strings check if the two strings' lengths do not differ by more than 1 return Math.abs(s.length() - t.length()) == 1; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/uber/ImplementTrie.java
company/uber/ImplementTrie.java
// Implement a trie with insert, search, and startsWith methods. // Note: // You may assume that all inputs are consist of lowercase letters a-z. // Your Trie object will be instantiated and called as such: // Trie trie = new Trie(); // trie.insert("somestring"); // trie.search("key"); class TrieNode { HashMap<Character, TrieNode> map; char character; boolean last; // Initialize your data structure here. public TrieNode(char character) { this.map = new HashMap<Character, TrieNode>(); this.character = character; this.last = false; } } public class ImplementTrie { private TrieNode root; public Trie() { root = new TrieNode(' '); } // Inserts a word into the trie. public void insert(String word) { TrieNode current = root; for(char c : word.toCharArray()) { if(!current.map.containsKey(c)) { current.map.put(c, new TrieNode(c)); } current = current.map.get(c); } current.last = true; } // Returns if the word is in the trie. public boolean search(String word) { TrieNode current = root; for(char c : word.toCharArray()) { if(!current.map.containsKey(c)) { return false; } current = current.map.get(c); } if(current.last == true) { return true; } else { return false; } } // Returns if there is any word in the trie // that starts with the given prefix. public boolean startsWith(String prefix) { TrieNode current = root; for(char c : prefix.toCharArray()) { if(!current.map.containsKey(c)) { return false; } current = current.map.get(c); } return true; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/uber/TwoSum.java
company/uber/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/uber/CloneGraph.java
company/uber/CloneGraph.java
// Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors. // OJ's undirected graph serialization: // Nodes are labeled uniquely. // We use # as a separator for each node, and , as a separator for node label and each neighbor of the node. // As an example, consider the serialized graph {0,1,2#1,2#2,2}. // The graph has a total of three nodes, and therefore contains three parts as separated by #. // First node is labeled as 0. Connect node 0 to both nodes 1 and 2. // Second node is labeled as 1. Connect node 1 to node 2. // Third node is labeled as 2. Connect node 2 to node 2 (itself), thus forming a self-cycle. // Visually, the graph looks like the following: // 1 // / \ // / \ // 0 --- 2 // / \ // \_/ /** * Definition for undirected graph. * class UndirectedGraphNode { * int label; * List<UndirectedGraphNode> neighbors; * UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<UndirectedGraphNode>(); } * }; */ public class CloneGraph { public HashMap<Integer, UndirectedGraphNode> map = new HashMap<Integer, UndirectedGraphNode>(); public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) { if(node == null) { return null; } if(map.containsKey(node.label)) { return map.get(node.label); } UndirectedGraphNode newNode = new UndirectedGraphNode(node.label); map.put(newNode.label, newNode); for(UndirectedGraphNode neighbor : node.neighbors) { newNode.neighbors.add(cloneGraph(neighbor)); } return newNode; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/uber/GroupShiftedStrings.java
company/uber/GroupShiftedStrings.java
// Given a string, we can "shift" each of its letter to its successive letter, for example: "abc" -> "bcd". We can keep "shifting" which forms the sequence: // "abc" -> "bcd" -> ... -> "xyz" // Given a list of strings which contains only lowercase alphabets, group all strings that belong to the same shifting sequence. // For example, given: ["abc", "bcd", "acef", "xyz", "az", "ba", "a", "z"], // A solution is: // [ // ["abc","bcd","xyz"], // ["az","ba"], // ["acef"], // ["a","z"] // ] public class GroupShiftedStrings { public List<List<String>> groupStrings(String[] strings) { List<List<String>> result = new ArrayList<List<String>>(); HashMap<String, List<String>> map = new HashMap<String, List<String>>(); for(String s : strings) { int offset = s.charAt(0) - 'a'; String key = ""; for(int i = 0; i < s.length(); i++) { char current = (char)(s.charAt(i) - offset); if(current < 'a') { current += 26; } key += current; } if(!map.containsKey(key)) { List<String> list = new ArrayList<String>(); map.put(key, list); } map.get(key).add(s); } for(String key : map.keySet()) { List<String> list = map.get(key); Collections.sort(list); result.add(list); } return result; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/uber/GenerateParentheses.java
company/uber/GenerateParentheses.java
class GenerateParentheses { public List<String> generateParenthesis(int n) { List<String> result = new ArrayList<String>(); generateParenthesisRecursive(result, "", 0, 0, n); return result; } public void generateParenthesisRecursive(List<String> result, String current, int open, int close, int n) { if(current.length() == n * 2) { result.add(current); return; } if(open < n) { generateParenthesisRecursive(result, current + "(", open + 1, close, n); } if(close < open) { generateParenthesisRecursive(result, current + ")", open, close + 1, n); } } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/uber/LetterCombinationsOfAPhoneNumber.java
company/uber/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/uber/PalindromePermutation.java
company/uber/PalindromePermutation.java
public class PalindromePermutation { public boolean canPermutePalindrome(String s) { char[] characters = new char[256]; for(int i = 0; i < s.length(); i++) { characters[s.charAt(i)]++; } int oddCount = 0; for(int i = 0; i < characters.length; i++) { if(!(characters[i] % 2 == 0)) { oddCount++; if(oddCount > 1) { return false; } } } return true; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/uber/MaximumDepthOfABinaryTree.java
company/uber/MaximumDepthOfABinaryTree.java
// Given a binary tree, find its maximum depth. // The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class MaximumDepthOfABinaryTree { public int maxDepth(TreeNode root) { if(root == null) { return 0; } return 1 + Math.max(maxDepth(root.left), maxDepth(root.right)); } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/uber/MinStack.java
company/uber/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/uber/RegularExpressionMatching.java
company/uber/RegularExpressionMatching.java
// Implement regular expression matching with support for '.' and '*'. // '.' Matches any single character. // '*' Matches zero or more of the preceding element. // The matching should cover the entire input string (not partial). // The function prototype should be: // bool isMatch(const char *s, const char *p) // Some examples: // isMatch("aa","a") → false // isMatch("aa","aa") → true // isMatch("aaa","aa") → false // isMatch("aa", "a*") → true // isMatch("aa", ".*") → true // isMatch("ab", ".*") → true // isMatch("aab", "c*a*b") → true public class RegularExpressionMatching { public boolean isMatch(String s, String p) { if(s == null || p == null) { return false; } boolean[][] dp = new boolean[s.length() + 1][p.length() + 1]; dp[0][0] = true; for(int i = 0; i < p.length(); i++) { if(p.charAt(i) == '*' && dp[0][i - 1]) { dp[0][i + 1] = true; } } for(int i = 0; i < s.length(); i++) { for(int j = 0; j < p.length(); j++) { if(p.charAt(j) == '.') { dp[i + 1][j + 1] = dp[i][j]; } if(p.charAt(j) == s.charAt(i)) { dp[i + 1][j + 1] = dp[i][j]; } if(p.charAt(j) == '*') { if(p.charAt(j - 1) != s.charAt(i) && p.charAt(j - 1) != '.') { dp[i + 1][j + 1] = dp[i + 1][j - 1]; } else { dp[i + 1][j + 1] = (dp[i + 1][j] || dp[i][j + 1] || dp[i + 1][j - 1]); } } } } return dp[s.length()][p.length()]; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/uber/SpiralMatrix.java
company/uber/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/uber/InsertDeleteGetRandomO1.java
company/uber/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/uber/RomanToInteger.java
company/uber/RomanToInteger.java
// Given a roman numeral, convert it to an integer. // Input is guaranteed to be within the range from 1 to 3999 public class RomanToInteger { public int romanToInt(String s) { HashMap<Character, Integer> map = new HashMap<Character, Integer>(); map.put('I', 1); map.put('V', 5); map.put('X', 10); map.put('L', 50); map.put('C', 100); map.put('D', 500); map.put('M', 1000); int total = 0; for(int i = 0; i < s.length() - 1; i++) { if(map.get(s.charAt(i)) < map.get(s.charAt(i + 1))) { total -= map.get(s.charAt(i)); } else { total += map.get(s.charAt(i)); } } total += map.get(s.charAt(s.length() - 1)); return total; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/uber/MinimumWindowSubstring.java
company/uber/MinimumWindowSubstring.java
// Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n). // For example, // S = "ADOBECODEBANC" // T = "ABC" // Minimum window is "BANC". // Note: // If there is no such window in S that covers all characters in T, return the empty string "". // If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S. public class MinimumWindowSubstring { public String minWindow(String s, String t) { HashMap<Character, Integer> map = new HashMap<>(); for(char c : s.toCharArray()) { map.put(c, 0); } for(char c : t.toCharArray()) { if(map.containsKey(c)) { map.put(c, map.get(c)+ 1); } else { return ""; } } int start = 0; int end = 0; int minStart = 0; int minLength = Integer.MAX_VALUE; int counter = t.length(); while(end < s.length()) { char c1 = s.charAt(end); if(map.get(c1) > 0) { counter--; } map.put(c1, map.get(c1) - 1); end++; while(counter == 0) { if(minLength > end - start) { minLength = end - start; minStart = start; } char c2 = s.charAt(start); map.put(c2, map.get(c2) + 1); if(map.get(c2) > 0) { counter++; } start++; } } return minLength == Integer.MAX_VALUE ? "" : s.substring(minStart, minStart + minLength); } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/uber/ValidSudoku.java
company/uber/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/uber/GroupAnagrams.java
company/uber/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/uber/Subsets.java
company/uber/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/uber/WordBreak.java
company/uber/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/uber/BestTimeToBuyOrSellStock.java
company/uber/BestTimeToBuyOrSellStock.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/uber/ExclusiveTimeOfFunctions.java
company/uber/ExclusiveTimeOfFunctions.java
//Given the running logs of n functions that are executed in a nonpreemptive single threaded CPU, find the exclusive time of these functions. //Each function has a unique id, start from 0 to n-1. A function may be called recursively or by another function. //A log is a string has this format : function_id:start_or_end:timestamp. For example, "0:start:0" means function 0 starts from the very beginning of time 0. "0:end:0" means function 0 ends to the very end of time 0. //Exclusive time of a function is defined as the time spent within this function, the time spent by calling other functions should not be considered as this function's exclusive time. You should return the exclusive time of each function sorted by their function id. //Example 1: //Input: //n = 2 //logs = //["0:start:0", //"1:start:2", //"1:end:5", //"0:end:6"] //Output:[3, 4] //Explanation: //Function 0 starts at time 0, then it executes 2 units of time and reaches the end of time 1. //Now function 0 calls function 1, function 1 starts at time 2, executes 4 units of time and end at time 5. //Function 0 is running again at time 6, and also end at the time 6, thus executes 1 unit of time. //So function 0 totally execute 2 + 1 = 3 units of time, and function 1 totally execute 4 units of time. //Note: //Input logs will be sorted by timestamp, NOT log id. //Your output should be sorted by function id, which means the 0th element of your output corresponds to the exclusive time of function 0. //Two functions won't start or end at the same time. //Functions could be called recursively, and will always end. //1 <= n <= 100 class ExclusiveTimeOfFunctions { public int[] exclusiveTime(int n, List<String> logs) { Stack<Integer> stack = new Stack <Integer>(); int[] result = new int[n]; String[] current = logs.get(0).split(":"); stack.push(Integer.parseInt(current[0])); int i = 1; int previous = Integer.parseInt(current[2]); while (i < logs.size()) { current = logs.get(i).split(":"); if (current[1].equals("start")) { if (!stack.isEmpty()) { result[stack.peek()] += Integer.parseInt(current[2]) - previous; } stack.push(Integer.parseInt(current[0])); previous = Integer.parseInt(current[2]); } else { result[stack.peek()] += Integer.parseInt(current[2]) - previous + 1; stack.pop(); previous = Integer.parseInt(current[2]) + 1; } i++; } return result; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/uber/SearchInRotatedSortedArray.java
company/uber/SearchInRotatedSortedArray.java
// Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. // (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). // You are given a target value to search. If found in the array return its index, otherwise return -1. // You may assume no duplicate exists in the array. public class SearchInRotatedSortedArray { public int search(int[] nums, int target) { int left = 0; int right = nums.length - 1; while(left <= right) { int mid = left + (right - left) / 2; if(nums[mid] == target) { return mid; } if(nums[left] <= nums[mid]) { if(target < nums[mid] && target >= nums[left]) { right = mid - 1; } else { left = mid + 1; } } if(nums[mid] <= nums[right]) { if(target > nums[mid] && target <= nums[right]) { left = mid + 1; } else { right = mid - 1; } } } return -1; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/uber/ValidPalindrome.java
company/uber/ValidPalindrome.java
public class ValidPalindrome { public boolean isPalindrome(String s) { int left = 0; int right = s.length() - 1; while(left < right) { while(!Character.isLetterOrDigit(s.charAt(left)) && left < right) { left++; } while(!Character.isLetterOrDigit(s.charAt(right)) && right > left) { right--; } if(Character.toLowerCase(s.charAt(left)) != Character.toLowerCase(s.charAt(right))) { return false; } left++; right--; } return true; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/google/BinaryTreeVerticalOrderTraversal.java
company/google/BinaryTreeVerticalOrderTraversal.java
// Given a binary tree, return the vertical order traversal of its nodes' values. (ie, from top to bottom, column by column). // If two nodes are in the same row and column, the order should be from left to right. // Examples: // Given binary tree [3,9,20,null,null,15,7], // 3 // /\ // / \ // 9 20 // /\ // / \ // 15 7 // return its vertical order traversal as: // [ // [9], // [3,15], // [20], // [7] // ] // Given binary tree [3,9,8,4,0,1,7], // 3 // /\ // / \ // 9 8 // /\ /\ // / \/ \ // 4 01 7 // return its vertical order traversal as: // [ // [4], // [9], // [3,0,1], // [8], // [7] // ] // Given binary tree [3,9,8,4,0,1,7,null,null,null,2,5] (0's right child is 2 and 1's left child is 5), // 3 // /\ // / \ // 9 8 // /\ /\ // / \/ \ // 4 01 7 // /\ // / \ // 5 2 // return its vertical order traversal as: // [ // [4], // [9,5], // [3,0,1], // [8,2], // [7] // ] /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class BinaryTreeVerticalOrderTraversal { public List<List<Integer>> verticalOrder(TreeNode root) { List<List<Integer>> result = new ArrayList<>(); if(root == null) { return result; } Map<Integer, ArrayList<Integer>> map = new HashMap<>(); Queue<TreeNode> q = new LinkedList<>(); Queue<Integer> cols = new LinkedList<>(); q.add(root); cols.add(0); int min = 0; int max = 0; while(!q.isEmpty()) { TreeNode node = q.poll(); int col = cols.poll(); if(!map.containsKey(col)) { map.put(col, new ArrayList<Integer>()); } map.get(col).add(node.val); if(node.left != null) { q.add(node.left); cols.add(col - 1); min = Math.min(min, col - 1); } if(node.right != null) { q.add(node.right); cols.add(col + 1); max = Math.max(max, col + 1); } } for(int i = min; i <= max; i++) { result.add(map.get(i)); } return result; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/google/PacificAtlanticWaterFlow.java
company/google/PacificAtlanticWaterFlow.java
// Given an m x n matrix of non-negative integers representing the height of each unit cell in a continent, the "Pacific ocean" touches the left and top edges of the matrix and the "Atlantic ocean" touches the right and bottom edges. // Water can only flow in four directions (up, down, left, or right) from a cell to another one with height equal or lower. // Find the list of grid coordinates where water can flow to both the Pacific and Atlantic ocean. // Note: // The order of returned grid coordinates does not matter. // Both m and n are less than 150. // Example: // Given the following 5x5 matrix: // Pacific ~ ~ ~ ~ ~ // ~ 1 2 2 3 (5) * // ~ 3 2 3 (4) (4) * // ~ 2 4 (5) 3 1 * // ~ (6) (7) 1 4 5 * // ~ (5) 1 1 2 4 * // * * * * * Atlantic // Return: // [[0, 4], [1, 3], [1, 4], [2, 2], [3, 0], [3, 1], [4, 0]] (positions with parentheses in above matrix). public class PacificAtlanticWaterFlow { public List<int[]> pacificAtlantic(int[][] matrix) { List<int[]> result = new LinkedList<>(); //error checking if(matrix == null || matrix.length == 0 || matrix[0].length == 0) { return result; } int n = matrix.length; int m = matrix[0].length; boolean[][] pacific = new boolean[n][m]; boolean[][] atlantic = new boolean[n][m]; for(int i = 0; i < n; i++) { dfs(matrix, pacific, Integer.MIN_VALUE, i, 0); dfs(matrix, atlantic, Integer.MIN_VALUE, i, m - 1); } for(int i = 0; i < m; i++) { dfs(matrix, pacific, Integer.MIN_VALUE, 0, i); dfs(matrix, atlantic, Integer.MIN_VALUE, n - 1, i); } for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { if(pacific[i][j] && atlantic[i][j]) { result.add(new int[] {i, j}); } } } return result; } public void dfs(int[][] matrix, boolean[][] visited, int height, int x, int y) { int n = matrix.length; int m = matrix[0].length; if(x < 0 || x >= n || y < 0 || y >= m || visited[x][y] || matrix[x][y] < height) { return; } visited[x][y] = true; dfs(matrix, visited, matrix[x][y], x + 1, y); dfs(matrix, visited, matrix[x][y], x - 1, y); dfs(matrix, visited, matrix[x][y], x, y + 1); dfs(matrix, visited, matrix[x][y], x, y - 1); } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/google/IslandPerimeter.java
company/google/IslandPerimeter.java
// You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represents water. Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells). The island doesn't have "lakes" (water inside that isn't connected to the water around the island). One cell is a square with side length 1. The grid is rectangular, width and height don't exceed 100. Determine the perimeter of the island. // Example: // [[0,1,0,0], // [1,1,1,0], // [0,1,0,0], // [1,1,0,0]] // Answer: 16 class IslandPerimeter { public int islandPerimeter(int[][] grid) { int perimeter = 0; if(grid == null || grid.length == 0) { return perimeter; } for(int i = 0; i < grid.length; i++) { for(int j = 0; j < grid[i].length; j++) { if(grid[i][j] == 1) { perimeter += numNeighbors(grid, i, j); return perimeter; } } } return perimeter; } public int numNeighbors(int[][] grid, int x, int y) { if(x < 0 || x >= grid.length || y < 0 || y >= grid[x].length || grid[x][y] == 0) { return 1; } if(grid[x][y] == -1) { return 0; } grid[x][y] = -1; return numNeighbors(grid, x + 1, y) + numNeighbors(grid, x - 1, y) + numNeighbors(grid, x, y + 1) + numNeighbors(grid, x, y - 1); } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/google/ClosestBinarySearchTreeValue.java
company/google/ClosestBinarySearchTreeValue.java
// Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target. // Note: // Given target value is a floating point. // You are guaranteed to have only one unique value in the BST that is closest to the target. /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class ClosestBinarySearchTreeValue { public int closestValue(TreeNode root, double target) { int value = root.val; TreeNode child = root.val < target ? root.right : root.left; if(child == null) { return value; } int childValue = closestValue(child, target); return Math.abs(value - target) < Math.abs(childValue - target) ? value : childValue; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/google/ExpressionAddOperators.java
company/google/ExpressionAddOperators.java
// Given a string that contains only digits 0-9 and a target value, return all possibilities to add binary operators (not unary) +, -, or * between the digits so they evaluate to the target value. // Examples: // "123", 6 -> ["1+2+3", "1*2*3"] // "232", 8 -> ["2*3+2", "2+3*2"] // "105", 5 -> ["1*0+5","10-5"] // "00", 0 -> ["0+0", "0-0", "0*0"] // "3456237490", 9191 -> [] public class ExpressionAddOperator { public List<String> addOperators(String num, int target) { List<String> result = new ArrayList<String>(); if(num == null || num.length() == 0) { return result; } helper(result, "", num, target, 0, 0, 0); return result; } public void helper(List<String> result, String path, String num, int target, int pos, long eval, long multed) { if(pos == num.length()) { if(eval == target) { result.add(path); } return; } for(int i = pos; i < num.length(); i++) { if(i != pos && num.charAt(pos) == '0') { break; } long cur = Long.parseLong(num.substring(pos, i + 1)); if(pos == 0) { helper(result, path + cur, num, target, i + 1, cur, cur); } else { helper(result, path + "+" + cur, num, target, i + 1, eval + cur, cur); helper(result, path + "-" + cur, num, target, i + 1, eval - cur, -cur); helper(result, path + "*" + cur, num, target, i + 1, eval - multed + multed * cur, multed * cur); } } } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/google/WordSquares.java
company/google/WordSquares.java
// Given a set of words (without duplicates), find all word squares you can build from them. // A sequence of words forms a valid word square if the kth row and column read the exact same string, where 0 ≤ k < max(numRows, numColumns). // For example, the word sequence ["ball","area","lead","lady"] forms a word square because each word reads the same both horizontally and vertically. // b a l l // a r e a // l e a d // l a d y // Note: // There are at least 1 and at most 1000 words. // All words will have the exact same length. // Word length is at least 1 and at most 5. // Each word contains only lowercase English alphabet a-z. public class WordSquares { public List<List<String>> wordSquares(String[] words) { List<List<String>> ret = new ArrayList<List<String>>(); if(words.length==0 || words[0].length()==0) { return ret; } Map<String, Set<String>> map = new HashMap<>(); int squareLen = words[0].length(); // create all prefix for(int i=0;i<words.length;i++){ for(int j=-1;j<words[0].length();j++){ if(!map.containsKey(words[i].substring(0, j+1))) { map.put(words[i].substring(0, j+1), new HashSet<String>()); } map.get(words[i].substring(0, j+1)).add(words[i]); } } helper(ret, new ArrayList<String>(), 0, squareLen, map); return ret; } public void helper(List<List<String>> ret, List<String> cur, int matched, int total, Map<String, Set<String>> map){ if(matched == total) { ret.add(new ArrayList<String>(cur)); return; } // build search string StringBuilder sb = new StringBuilder(); for(int i=0;i<=matched-1;i++) { sb.append(cur.get(i).charAt(matched)); } // bachtracking Set<String> cand = map.get(sb.toString()); if(cand==null) { return; } for(String str:cand){ cur.add(str); helper(ret, cur, matched+1, total, map); cur.remove(cur.size()-1); } } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/google/NumberOfIslands.java
company/google/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/google/EncodeAndDecodeTinyURL.java
company/google/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/google/ImplementTrie.java
company/google/ImplementTrie.java
// Implement a trie with insert, search, and startsWith methods. // Note: // You may assume that all inputs are consist of lowercase letters a-z. // Your Trie object will be instantiated and called as such: // Trie trie = new Trie(); // trie.insert("somestring"); // trie.search("key"); class TrieNode { HashMap<Character, TrieNode> map; char character; boolean last; // Initialize your data structure here. public TrieNode(char character) { this.map = new HashMap<Character, TrieNode>(); this.character = character; this.last = false; } } public class Trie { private TrieNode root; public Trie() { root = new TrieNode(' '); } // Inserts a word into the trie. public void insert(String word) { TrieNode current = root; for(char c : word.toCharArray()) { if(!current.map.containsKey(c)) { current.map.put(c, new TrieNode(c)); } current = current.map.get(c); } current.last = true; } // Returns if the word is in the trie. public boolean search(String word) { TrieNode current = root; for(char c : word.toCharArray()) { if(!current.map.containsKey(c)) { return false; } current = current.map.get(c); } if(current.last == true) { return true; } else { return false; } } // Returns if there is any word in the trie // that starts with the given prefix. public boolean startsWith(String prefix) { TrieNode current = root; for(char c : prefix.toCharArray()) { if(!current.map.containsKey(c)) { return false; } current = current.map.get(c); } return true; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/google/PaintFence.java
company/google/PaintFence.java
// There is a fence with n posts, each post can be painted with one of the k colors. // You have to paint all the posts such that no more than two adjacent fence posts have the same color. // Return the total number of ways you can paint the fence. // Note: // n and k are non-negative integers. public class PaintFence { public int numWays(int n, int k) { if(n <= 0) { return 0; } int sameColorCounts = 0; int differentColorCounts = k; for(int i = 2; i <= n; i++) { int temp = differentColorCounts; differentColorCounts = (sameColorCounts + differentColorCounts) * (k - 1); sameColorCounts = temp; } return sameColorCounts + differentColorCounts; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/google/PlusOne.java
company/google/PlusOne.java
//Given a non-empty array of digits representing a non-negative integer, plus one to the integer. // //The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit. // //You may assume the integer does not contain any leading zero, except the number 0 itself. // //Example 1: // //Input: [1,2,3] //Output: [1,2,4] //Explanation: The array represents the integer 123. //Example 2: // //Input: [4,3,2,1] //Output: [4,3,2,2] //Explanation: The array represents the integer 4321. class Solution { public int[] plusOne(int[] digits) { for(int i = digits.length - 1; i >= 0; i--) { if(digits[i] < 9) { digits[i]++; return digits; } digits[i] = 0; } int[] result = new int[digits.length + 1]; result[0] = 1; return result; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/google/FirstUniqueCharacterInAString.java
company/google/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/google/LoggerRateLimiter.java
company/google/LoggerRateLimiter.java
// Design a logger system that receive stream of messages along with its timestamps, each message should be printed if and only if it is not printed in the last 10 seconds. // Given a message and a timestamp (in seconds granularity), return true if the message should be printed in the given timestamp, otherwise returns false. // It is possible that several messages arrive roughly at the same time. // Example: // Logger logger = new Logger(); // // logging string "foo" at timestamp 1 // logger.shouldPrintMessage(1, "foo"); returns true; // // logging string "bar" at timestamp 2 // logger.shouldPrintMessage(2,"bar"); returns true; // // logging string "foo" at timestamp 3 // logger.shouldPrintMessage(3,"foo"); returns false; // // logging string "bar" at timestamp 8 // logger.shouldPrintMessage(8,"bar"); returns false; // // logging string "foo" at timestamp 10 // logger.shouldPrintMessage(10,"foo"); returns false; // // logging string "foo" at timestamp 11 // logger.shouldPrintMessage(11,"foo"); returns true; public class LoggerRateLimiter { HashMap<String, Integer> messages; /** Initialize your data structure here. */ public Logger() { this.messages = new HashMap<String, Integer>(); } /** Returns true if the message should be printed in the given timestamp, otherwise returns false. If this method returns false, the message will not be printed. The timestamp is in seconds granularity. */ public boolean shouldPrintMessage(int timestamp, String message) { if(messages.containsKey(message)) { if(timestamp - messages.get(message) >= 10) { messages.put(message, timestamp); return true; } else { return false; } } else { messages.put(message, timestamp); return true; } } } /** * Your Logger object will be instantiated and called as such: * Logger obj = new Logger(); * boolean param_1 = obj.shouldPrintMessage(timestamp,message); */
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/google/CloneGraph.java
company/google/CloneGraph.java
// Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors. // OJ's undirected graph serialization: // Nodes are labeled uniquely. // We use # as a separator for each node, and , as a separator for node label and each neighbor of the node. // As an example, consider the serialized graph {0,1,2#1,2#2,2}. // The graph has a total of three nodes, and therefore contains three parts as separated by #. // First node is labeled as 0. Connect node 0 to both nodes 1 and 2. // Second node is labeled as 1. Connect node 1 to node 2. // Third node is labeled as 2. Connect node 2 to node 2 (itself), thus forming a self-cycle. // Visually, the graph looks like the following: // 1 // / \ // / \ // 0 --- 2 // / \ // \_/ /** * Definition for undirected graph. * class UndirectedGraphNode { * int label; * List<UndirectedGraphNode> neighbors; * UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<UndirectedGraphNode>(); } * }; */ public class CloneGraph { public HashMap<Integer, UndirectedGraphNode> map = new HashMap<Integer, UndirectedGraphNode>(); public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) { if(node == null) { return null; } if(map.containsKey(node.label)) { return map.get(node.label); } UndirectedGraphNode newNode = new UndirectedGraphNode(node.label); map.put(newNode.label, newNode); for(UndirectedGraphNode neighbor : node.neighbors) { newNode.neighbors.add(cloneGraph(neighbor)); } return newNode; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/google/PlusOneLinkedList.java
company/google/PlusOneLinkedList.java
// Given a non-negative integer represented as non-empty a singly linked list of digits, plus one to the integer. // You may assume the integer do not contain any leading zero, except the number 0 itself. // The digits are stored such that the most significant digit is at the head of the list. // Example: // Input: // 1->2->3 // Output: // 1->2->4 /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class PlusOneLinkedList { public ListNode plusOne(ListNode head) { if(plusOneRecursive(head) == 0) { return head; } else { ListNode newHead = new ListNode(1); newHead.next = head; return newHead; } } private int plusOneRecursive(ListNode head) { if(head == null) { return 1; } int carry = plusOneRecursive(head.next); if(carry == 0) { return 0; } int value = head.val + 1; head.val = value % 10; return value/10; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/google/MergeIntervals.java
company/google/MergeIntervals.java
// Given a collection of intervals, merge all overlapping intervals. // For example, // Given [1,3],[2,6],[8,10],[15,18], // return [1,6],[8,10],[15,18]. /** * 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; } * } */ class MergeIntervals { public List<Interval> merge(List<Interval> intervals) { List<Interval> result = new ArrayList<Interval>(); if(intervals == null || intervals.size() == 0) { return result; } Interval[] allIntervals = intervals.toArray(new Interval[intervals.size()]); Arrays.sort(allIntervals, new Comparator<Interval>() { public int compare(Interval a, Interval b) { if(a.start == b.start) { return a.end - b.end; } return a.start - b.start; } }); for(Interval i: allIntervals) { if (result.size() == 0 || result.get(result.size() - 1).end < i.start) { result.add(i); } else { result.get(result.size() - 1).end = Math.max(result.get(result.size() - 1).end, i.end); } } return result; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/google/GroupShiftedStrings.java
company/google/GroupShiftedStrings.java
// Given a string, we can "shift" each of its letter to its successive letter, for example: "abc" -> "bcd". We can keep "shifting" which forms the sequence: // "abc" -> "bcd" -> ... -> "xyz" // Given a list of strings which contains only lowercase alphabets, group all strings that belong to the same shifting sequence. // For example, given: ["abc", "bcd", "acef", "xyz", "az", "ba", "a", "z"], // A solution is: // [ // ["abc","bcd","xyz"], // ["az","ba"], // ["acef"], // ["a","z"] // ] public class GroupShiftedStrings { public List<List<String>> groupStrings(String[] strings) { List<List<String>> result = new ArrayList<List<String>>(); HashMap<String, List<String>> map = new HashMap<String, List<String>>(); for(String s : strings) { int offset = s.charAt(0) - 'a'; String key = ""; for(int i = 0; i < s.length(); i++) { char current = (char)(s.charAt(i) - offset); if(current < 'a') { current += 26; } key += current; } if(!map.containsKey(key)) { List<String> list = new ArrayList<String>(); map.put(key, list); } map.get(key).add(s); } for(String key : map.keySet()) { List<String> list = map.get(key); Collections.sort(list); result.add(list); } return result; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/google/GenerateParentheses.java
company/google/GenerateParentheses.java
//Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. // //For example, given n = 3, a solution set is: // //[ //"((()))", //"(()())", //"(())()", //"()(())", //"()()()" //] class GenerateParentheses { public List<String> generateParenthesis(int n) { List<String> result = new ArrayList<String>(); generateParenthesisRecursive(result, "", 0, 0, n); return result; } public void generateParenthesisRecursive(List<String> result, String current, int open, int close, int n) { if(current.length() == n * 2) { result.add(current); return; } if(open < n) { generateParenthesisRecursive(result, current + "(", open + 1, close, n); } if(close < open) { generateParenthesisRecursive(result, current + ")", open, close + 1, n); } } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/google/LetterCombinationsOfAPhoneNumber.java
company/google/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/google/DailyTemperatures.java
company/google/DailyTemperatures.java
//Given a list of daily temperatures, produce a list that, for each day in the input, tells you how many days you would have to wait until a warmer temperature. If there is no future day for which this is possible, put 0 instead. // //For example, given the list temperatures = [73, 74, 75, 71, 69, 72, 76, 73], your output should be [1, 1, 4, 2, 1, 1, 0, 0]. // //Note: The length of temperatures will be in the range [1, 30000]. Each temperature will be an integer in the range [30, 100]. class DailyTemperatures { public int[] dailyTemperatures(int[] temperatures) { int[] result = new int[temperatures.length]; Stack<Integer> stack = new Stack<Integer>(); for(int i = 0; i < temperatures.length; i++) { while(!stack.isEmpty() && temperatures[i] > temperatures[stack.peek()]) { int index = stack.pop(); result[index] = i - index; } stack.push(i); } return result; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/google/AndroidUnlockPatterns.java
company/google/AndroidUnlockPatterns.java
// Given an Android 3x3 key lock screen and two integers m and n, where 1 ≤ m ≤ n ≤ 9, count the total number of unlock patterns of the Android lock screen, which consist of minimum of m keys and maximum n keys. // Rules for a valid pattern: // Each pattern must connect at least m keys and at most n keys. // All the keys must be distinct. // If the line connecting two consecutive keys in the pattern passes through any other keys, the other keys must have previously selected in the pattern. No jumps through non selected key is allowed. // The order of keys used matters. // Explanation: // | 1 | 2 | 3 | // | 4 | 5 | 6 | // | 7 | 8 | 9 | // Invalid move: 4 - 1 - 3 - 6 // Line 1 - 3 passes through key 2 which had not been selected in the pattern. // Invalid move: 4 - 1 - 9 - 2 // Line 1 - 9 passes through key 5 which had not been selected in the pattern. // Valid move: 2 - 4 - 1 - 3 - 6 // Line 1 - 3 is valid because it passes through key 2, which had been selected in the pattern // Valid move: 6 - 5 - 4 - 1 - 9 - 2 // Line 1 - 9 is valid because it passes through key 5, which had been selected in the pattern. // Example: // Given m = 1, n = 1, return 9. public class AndroidUnlockPatterns { public int numberOfPatterns(int m, int n) { //initialize a 10x10 matrix int skip[][] = new int[10][10]; //initialize indices of skip matrix (all other indices in matrix are 0 by default) skip[1][3] = skip[3][1] = 2; skip[1][7] = skip[7][1] = 4; skip[3][9] = skip[9][3] = 6; skip[7][9] = skip[9][7] = 8; skip[1][9] = skip[9][1] = skip[2][8] = skip[8][2] = skip[3][7] = skip [7][3] = skip[6][4] = skip[4][6] = 5; //initialize visited array boolean visited[] = new boolean[10]; //initialize total number to 0 int totalNumber = 0; //run DFS for each length from m to n for(int i = m; i <= n; ++i) { totalNumber += DFS(visited, skip, 1, i - 1) * 4; //1, 3, 7, and 9 are symmetric so multiply this result by 4 totalNumber += DFS(visited, skip, 2, i - 1) * 4; //2, 4, 6, and 8 are symmetric so multiply this result by 4 totalNumber += DFS(visited, skip, 5, i - 1); //do not multiply by 4 because 5 is unique } return totalNumber; } int DFS(boolean visited[], int[][] skip, int current, int remaining) { //base cases if(remaining < 0) { return 0; } if(remaining == 0) { return 1; } //mark the current node as visited visited[current] = true; //initialize total number to 0 int totalNumber = 0; for(int i = 1; i <= 9; ++i) { //if the current node has not been visited and (two numbers are adjacent or skip number has already been visited) if(!visited[i] && (skip[current][i] == 0 || visited[skip[current][i]])) { totalNumber += DFS(visited, skip, i, remaining - 1); } } //mark the current node as not visited visited[current] = false; //return total number return totalNumber; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/google/ShortestDistanceFromAllBuildings.java
company/google/ShortestDistanceFromAllBuildings.java
// You want to build a house on an empty land which reaches all buildings in the shortest amount of distance. You can only move up, down, left and right. You are given a 2D grid of values 0, 1 or 2, where: // Each 0 marks an empty land which you can pass by freely. // Each 1 marks a building which you cannot pass through. // Each 2 marks an obstacle which you cannot pass through. // For example, given three buildings at (0,0), (0,4), (2,2), and an obstacle at (0,2): // 1 - 0 - 2 - 0 - 1 // | | | | | // 0 - 0 - 0 - 0 - 0 // | | | | | // 0 - 0 - 1 - 0 - 0 // The point (1,2) is an ideal empty land to build a house, as the total travel distance of 3+3+1=7 is minimal. So return 7. // Note: // There will be at least one building. If it is not possible to build such house according to the above rules, return -1. public class ShortestDistanceFromAllBuildings { public int shortestDistance(int[][] grid) { if(grid == null || grid.length == 0 || grid[0].length == 0) { return -1; } final int[] shift = {0, 1, 0, -1, 0}; int rows = grid.length; int columns = grid[0].length; int[][] distance = new int[rows][columns]; int[][] reach = new int[rows][columns]; int numberOfBuildings = 0; for(int i = 0; i < rows; i++) { for(int j = 0; j < columns; j++) { if(grid[i][j] == 1) { numberOfBuildings++; Queue<int[]> queue = new LinkedList<int[]>(); queue.offer(new int[] {i, j}); boolean[][] visited = new boolean[rows][columns]; int relativeDistance = 1; while(!queue.isEmpty()) { int qSize = queue.size(); for(int q = 0; q < qSize; q++) { int[] current = queue.poll(); for(int k = 0; k < 4; k++) { int nextRow = current[0] + shift[k]; int nextColumn = current[1] + shift[k + 1]; if(nextRow >= 0 && nextRow < rows && nextColumn >= 0 && nextColumn < columns && grid[nextRow][nextColumn] == 0 && !visited[nextRow][nextColumn]) { distance[nextRow][nextColumn] += relativeDistance; reach[nextRow][nextColumn]++; visited[nextRow][nextColumn] = true; queue.offer(new int[] {nextRow, nextColumn}); } } } relativeDistance++; } } } } int shortest = Integer.MAX_VALUE; for(int i = 0; i < rows; i++) { for(int j = 0; j < columns; j++) { if(grid[i][j] == 0 && reach[i][j] == numberOfBuildings) { shortest = Math.min(shortest, distance[i][j]); } } } return shortest == Integer.MAX_VALUE ? -1 : shortest; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/google/3SumSmaller.java
company/google/3SumSmaller.java
// Given an array of n integers nums and a target, find the number of index triplets i, j, k with 0 <= i < j < k < n that satisfy the condition nums[i] + nums[j] + nums[k] < target. // For example, given nums = [-2, 0, 1, 3], and target = 2. // Return 2. Because there are two triplets which sums are less than 2: // [-2, 0, 1] // [-2, 0, 3] // Follow up: // Could you solve it in O(n2) runtime? public class 3SumSmaller { public int threeSumSmaller(int[] nums, int target) { //initialize total count to zero int count = 0; //sort the array Arrays.sort(nums); //loop through entire array for(int i = 0; i < nums.length - 2; i++) { //set left to i + 1 int left = i + 1; //set right to end of array int right = nums.length - 1; //while left index < right index while(left < right) { //if the 3 indices add to less than the target increment count if(nums[i] + nums[left] + nums[right] < target) { //increment the count by the distance between left and right because the array is sorted count += right - left; //increment left pointer left++; } else { //if they sum to a value greater than target... //decrement right pointer right--; } } } return count; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/google/UniqueWordAbbreviation.java
company/google/UniqueWordAbbreviation.java
// An abbreviation of a word follows the form <first letter><number><last letter>. Below are some examples of word abbreviations: // a) it --> it (no abbreviation) // 1 // b) d|o|g --> d1g // 1 1 1 // 1---5----0----5--8 // c) i|nternationalizatio|n --> i18n // 1 // 1---5----0 // d) l|ocalizatio|n --> l10n // Assume you have a dictionary and given a word, find whether its abbreviation is unique in the dictionary. A word's abbreviation is unique if no other word from the dictionary has the same abbreviation. // Example: // Given dictionary = [ "deer", "door", "cake", "card" ] // isUnique("dear") -> // false // isUnique("cart") -> // true // isUnique("cane") -> // false // isUnique("make") -> // true import java.util.ArrayList; public class UniqueWordAbbreviation { HashMap<String, String> map; public ValidWordAbbr(String[] dictionary) { this.map = new HashMap<String, String>(); for(String word : dictionary) { String key = getKey(word); if(map.containsKey(key)) { if(!map.get(key).equals(word)) { map.put(key, ""); } } else { map.put(key, word); } } } public boolean isUnique(String word) { return !map.containsKey(getKey(word))||map.get(getKey(word)).equals(word); } public String getKey(String word) { if(word.length() <= 2) { return word; } return word.charAt(0) + Integer.toString(word.length() - 2) + word.charAt(word.length() - 1); } } // Your ValidWordAbbr object will be instantiated and called as such: // ValidWordAbbr vwa = new ValidWordAbbr(dictionary); // vwa.isUnique("Word"); // vwa.isUnique("anotherWord");
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false