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/leetcode/hash-table/InsertDeleteGetRandomO1.java
leetcode/hash-table/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/leetcode/hash-table/ValidAnagram.java
leetcode/hash-table/ValidAnagram.java
class ValidAnagram { public boolean isAnagram(String s, String t) { HashMap<Character, Integer> map = new HashMap<Character, Integer>(); for(char c: s.toCharArray()) { if(map.containsKey(c)) { map.put(c, map.get(c) + 1); } else { map.put(c, 1); } } for(char c: t.toCharArray()) { if(map.containsKey(c)) { map.put(c, map.get(c) - 1); } else { return false; } } for(char c: map.keySet()) { if(map.get(c) != 0) { return false; } } return true; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/hash-table/MinimumWindowSubstring.java
leetcode/hash-table/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/leetcode/hash-table/BullsAndCows.java
leetcode/hash-table/BullsAndCows.java
//You are playing the following Bulls and Cows game with your friend: You write down a number and ask your friend to guess what the number is. Each time your friend makes a guess, you provide a hint that indicates how many digits in said guess match your secret number exactly in both digit and position (called "bulls") and how many digits match the secret number but locate in the wrong position (called "cows"). Your friend will use successive guesses and hints to eventually derive the secret number. // //Write a function to return a hint according to the secret number and friend's guess, use A to indicate the bulls and B to indicate the cows. // //Please note that both secret number and friend's guess may contain duplicate digits. // //Example 1: // //Input: secret = "1807", guess = "7810" // //Output: "1A3B" // //Explanation: 1 bull and 3 cows. The bull is 8, the cows are 0, 1 and 7. //Example 2: // //Input: secret = "1123", guess = "0111" // //Output: "1A1B" // //Explanation: The 1st 1 in friend's guess is a bull, the 2nd or 3rd 1 is a cow. //Note: You may assume that the secret number and your friend's guess only contain digits, and their lengths are always equal. class BullsAndCows { public String getHint(String secret, String guess) { int bulls = 0; int cows = 0; int[] counts = new int[10]; for(int i = 0; i < secret.length(); i++) { if(secret.charAt(i) == guess.charAt(i)) { bulls++; } else { if(counts[secret.charAt(i) - '0']++ < 0) { cows++; } if(counts[guess.charAt(i) - '0']-- > 0) { cows++; } } } return bulls + "A" + cows + "B"; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/hash-table/FindAnagramMappings.java
leetcode/hash-table/FindAnagramMappings.java
//Given two lists Aand B, and B is an anagram of A. B is an anagram of A means B is made by randomizing the order of the elements in A. //We want to find an index mapping P, from A to B. A mapping P[i] = j means the ith element in A appears in B at index j. //These lists A and B may contain duplicates. If there are multiple answers, output any of them. //For example, given //A = [12, 28, 46, 32, 50] //B = [50, 12, 32, 46, 28] //We should return //[1, 4, 3, 2, 0] //as P[0] = 1 because the 0th element of A appears at B[1], and P[1] = 4 because the 1st element of A appears at B[4], and so on. class FindAnagramMappings { public int[] anagramMappings(int[] A, int[] B) { int[] mapping = new int[A.length]; HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); for(int i = 0; i < B.length; i++) { map.put(B[i], i); } for(int i = 0; i < A.length; i++) { mapping[i] = map.get(A[i]); } return mapping; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/hash-table/ValidSudoku.java
leetcode/hash-table/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/leetcode/hash-table/StrobogrammaticNumber.java
leetcode/hash-table/StrobogrammaticNumber.java
// A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down). // Write a function to determine if a number is strobogrammatic. The number is represented as a string. // For example, the numbers "69", "88", and "818" are all strobogrammatic. public class StrobogrammaticNumber { public boolean isStrobogrammatic(String num) { for(int i = 0, j = num.length() - 1; i <= j; i++, j--) { if(!"00 11 88 696".contains(num.charAt(i) + "" + num.charAt(j))) { return false; } } return true; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/hash-table/GroupAnagrams.java
leetcode/hash-table/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/leetcode/hash-table/ContainsDuplicate.java
leetcode/hash-table/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/leetcode/hash-table/FindTheDifference.java
leetcode/hash-table/FindTheDifference.java
// Given two strings s and t which consist of only lowercase letters. // String t is generated by random shuffling string s and then add one more letter at a random position. // Find the letter that was added in t. // Example: // Input: // s = "abcd" // t = "abcde" // Output: // e // Explanation: // 'e' is the letter that was added. public class FindTheDifference { public char findTheDifference(String s, String t) { int charCodeS = 0; int charCodeT = 0; for(int i = 0; i < s.length(); i++) { charCodeS += (int)(s.charAt(i)); } for(int i = 0; i < t.length(); i++) { charCodeT += (int)(t.charAt(i)); } return (char)(charCodeT - charCodeS); } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/hash-table/SparseMatrixMultiplication.java
leetcode/hash-table/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/leetcode/tree/BinaryTreeMaximumPathSum.java
leetcode/tree/BinaryTreeMaximumPathSum.java
// Given a binary tree, find the maximum path sum. // For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root. // For example: // Given the below binary tree, // 1 // / \ // 2 3 // Return 6. /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class BinaryTreeMaximumPathSum { int max = Integer.MIN_VALUE; public int maxPathSum(TreeNode root) { maxPathSumRecursive(root); return max; } private int maxPathSumRecursive(TreeNode root) { if(root == null) { return 0; } int left = Math.max(maxPathSumRecursive(root.left), 0); int right = Math.max(maxPathSumRecursive(root.right), 0); max = Math.max(max, root.val + left + right); return root.val + Math.max(left, right); } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/tree/InorderSuccessorInBST.java
leetcode/tree/InorderSuccessorInBST.java
// Given a binary search tree and a node in it, find the in-order successor of that node in the BST. // Note: If the given node has no in-order successor in the tree, return null. /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class InorderSuccessorInBST { public TreeNode inorderSuccessor(TreeNode root, TreeNode p) { TreeNode successor = null; while(root != null) { if(p.val < root.val) { successor = root; root = root.left; } else { root = root.right; } } return successor; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/tree/BinaryTreePaths.java
leetcode/tree/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/leetcode/tree/TrimABinarySearchTree.java
leetcode/tree/TrimABinarySearchTree.java
//Given a binary search tree and the lowest and highest boundaries as L and R, trim the //tree so that all its elements lies in [L, R] (R >= L). You might need to change the root //of the tree, so the result should return the new root of the trimmed binary search tree. /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class TrimABinarySearchTree { public TreeNode trimBST(TreeNode root, int L, int R) { if(root == null) { return root; } if(root.val < L) { return trimBST(root.right, L, R); } if(root.val > R) { return trimBST(root.left, L, R); } root.left = trimBST(root.left, L, R); root.right = trimBST(root.right, L, R); return root; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/tree/LowestCommonAncestorOfABinaryTree.java
leetcode/tree/LowestCommonAncestorOfABinaryTree.java
// Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. // According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).” // _______3______ // / \ // ___5__ ___1__ // / \ / \ // 6 _2 0 8 // / \ // 7 4 // For example, the lowest common ancestor (LCA) of nodes 5 and 1 is 3. Another example is LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition. /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class LowestCommonAncestorOfABinaryTree { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if(root == null || root == p || root == q) { return root; } TreeNode left = lowestCommonAncestor(root.left, p, q); TreeNode right = lowestCommonAncestor(root.right, p, q); if(left != null && right != null) { return root; } return left == null ? right : left; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/tree/InvertBinaryTree.java
leetcode/tree/InvertBinaryTree.java
// Invert a binary tree. // 4 // / \ // 2 7 // / \ / \ // 1 3 6 9 // to // 4 // / \ // 7 2 // / \ / \ // 9 6 3 1 /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class InvertBinaryTree { public TreeNode invertTree(TreeNode root) { if(root == null) { return root; } TreeNode temp = root.left; root.left = invertTree(root.right); root.right = invertTree(temp); return root; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/tree/SumOfLeftLeaves.java
leetcode/tree/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/leetcode/tree/ValidateBinarySearchTree.java
leetcode/tree/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/palantir/ContainsDuplicatesII.java
company/palantir/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/palantir/ContainsDuplicate.java
company/palantir/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/apple/ReverseWordsInAString.java
company/apple/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/apple/ValidSudoku.java
company/apple/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/yelp/ReverseWordsInAString.java
company/yelp/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/yelp/InsertDeleteGetRandomO1.java
company/yelp/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/adobe/AddDigits.java
company/adobe/AddDigits.java
//Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. //For example: //Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it. //Follow up: //Could you do it without any loop/recursion in O(1) runtime? class AddDigits { public int addDigits(int num) { while(num >= 10) { int temp = 0; while(num > 0) { temp += num % 10; num /= 10; } num = temp; } return num; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/adobe/MajorityElement.java
company/adobe/MajorityElement.java
//Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times. //You may assume that the array is non-empty and the majority element always exist in the array. class MajorityElement { public int majorityElement(int[] nums) { if(nums.length == 1) { return nums[0]; } HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); for(int current: nums) { if(map.containsKey(current) && map.get(current) + 1 > nums.length / 2) { return current; } else if(map.containsKey(current)) { map.put(current, map.get(current) + 1); } else { map.put(current, 1); } } //no majority element exists return -1; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/twitter/ReverseLinkedList.java
company/twitter/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/twitter/MergeKSortedLists.java
company/twitter/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/twitter/OneEditDistance.java
company/twitter/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/twitter/ImplementTrie.java
company/twitter/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/twitter/MergeIntervals.java
company/twitter/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/twitter/MultiplyStrings.java
company/twitter/MultiplyStrings.java
// Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2. // Note: // The length of both num1 and num2 is < 110. // Both num1 and num2 contains only digits 0-9. // Both num1 and num2 does not contain any leading zero. // You must not use any built-in BigInteger library or convert the inputs to integer directly. public class MultiplyStrings { public String multiply(String num1, String num2) { int m = num1.length(); int n = num2.length(); int[] pos = new int[m + n]; for(int i = m - 1; i >= 0; i--) { for(int j = n - 1; j >= 0; j--) { int mul = (num1.charAt(i) - '0') * (num2.charAt(j) - '0'); int p1 = i + j; int p2 = i + j + 1; int sum = mul + pos[p2]; pos[p1] += sum / 10; pos[p2] = (sum) % 10; } } StringBuilder sb = new StringBuilder(); for(int p : pos) { if(!(sb.length() == 0 && p == 0)) { sb.append(p); } } return sb.length() == 0 ? "0" : sb.toString(); } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/twitter/RegularExpressionMatching.java
company/twitter/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/twitter/InsertDeleteGetRandomO1.java
company/twitter/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/twitter/ValidParentheses.java
company/twitter/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/twitter/FlattenNestedListIterator.java
company/twitter/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/twitter/TrappingRainWater.java
company/twitter/TrappingRainWater.java
// Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining. // For example, // Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6. public class TrappingRainWater { public int trap(int[] height) { int water = 0; int leftIndex = 0; int rightIndex = height.length - 1; int leftMax = 0; int rightMax = 0; while(leftIndex <= rightIndex) { leftMax = Math.max(leftMax, height[leftIndex]); rightMax = Math.max(rightMax, height[rightIndex]); if(leftMax < rightMax) { water += leftMax - height[leftIndex]; leftIndex++; } else { water += rightMax - height[rightIndex]; rightIndex--; } } return water; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/twitter/LowestCommonAncestorOfABinaryTree.java
company/twitter/LowestCommonAncestorOfABinaryTree.java
// Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. // According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).” // _______3______ // / \ // ___5__ ___1__ // / \ / \ // 6 _2 0 8 // / \ // 7 4 // For example, the lowest common ancestor (LCA) of nodes 5 and 1 is 3. Another example is LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition. /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class LowestCommonAncestorOfABinaryTree { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if(root == null || root == p || root == q) { return root; } TreeNode left = lowestCommonAncestor(root.left, p, q); TreeNode right = lowestCommonAncestor(root.right, p, q); if(left != null && right != null) { return root; } return left == null ? right : left; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/microsoft/LinkedListCycle.java
company/microsoft/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/microsoft/LongestIncreasingSubsequence.java
company/microsoft/LongestIncreasingSubsequence.java
//Given an unsorted array of integers, find the length of longest increasing subsequence. //For example, //Given [10, 9, 2, 5, 3, 7, 101, 18], //The longest increasing subsequence is [2, 3, 7, 101], therefore the length is 4. Note that there may be more than one LIS combination, it is only necessary for you to return the length. //Your algorithm should run in O(n2) complexity. //Follow up: Could you improve it to O(n log n) time complexity? class LongestIncreasingSubsequence { public int lengthOfLIS(int[] nums) { if(nums == null || nums.length < 1) { return 0; } int[] dp = new int[nums.length]; dp[0] = 1; int max = 1; for(int i = 1; i < dp.length; i++) { int currentMax = 0; for(int j = 0; j < i; j++) { if(nums[i] > nums[j]) { currentMax = Math.max(currentMax, dp[j]); } } dp[i] = 1 + currentMax; max = Math.max(max, dp[i]); } return max; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/microsoft/FirstUniqueCharacterInAString.java
company/microsoft/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/microsoft/ReverseWordsInAString.java
company/microsoft/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/microsoft/AddDigits.java
company/microsoft/AddDigits.java
//Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. //For example: //Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it. //Follow up: //Could you do it without any loop/recursion in O(1) runtime? class AddDigits { public int addDigits(int num) { while(num >= 10) { int temp = 0; while(num > 0) { temp += num % 10; num /= 10; } num = temp; } return num; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/microsoft/SpiralMatrix.java
company/microsoft/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/microsoft/LongestPalindromicSubstring.java
company/microsoft/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/microsoft/Permutations.java
company/microsoft/Permutations.java
//Given a collection of distinct numbers, return all possible permutations. // //For example, //[1,2,3] have the following permutations: //[ //[1,2,3], //[1,3,2], //[2,1,3], //[2,3,1], //[3,1,2], //[3,2,1] //] class Permutations { public List<List<Integer>> permute(int[] nums) { LinkedList<List<Integer>> result = new LinkedList<List<Integer>>(); result.add(new ArrayList<Integer>()); for (int n: nums) { int size = result.size(); while(size > 0) { List<Integer> current = result.pollFirst(); for (int i = 0; i <= current.size(); i++) { List<Integer> temp = new ArrayList<Integer>(current); temp.add(i, n); result.add(temp); } size--; } } return result; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/microsoft/HouseRobberII.java
company/microsoft/HouseRobberII.java
//Note: This is an extension of House Robber. (security system is tripped if two ajacent houses are robbed) //After robbing those houses on that street, the thief has found himself a new place for his thievery so that //he will not get too much attention. This time, all houses at this place are arranged in a circle. That means //the first house is the neighbor of the last one. Meanwhile, the security system for these houses remain the //same as for those in the previous street. //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. class HouseRobberII { public int rob(int[] nums) { if (nums.length == 0) { return 0; } if (nums.length < 2) { return nums[0]; } int[] first = new int[nums.length + 1]; int[] second = new int[nums.length + 1]; first[0] = 0; first[1] = nums[0]; second[0] = 0; second[1] = 0; for (int i = 2; i <= nums.length; i++) { first[i] = Math.max(first[i - 1], first[i - 2] + nums[i - 1]); second[i] = Math.max(second[i - 1], second[i - 2] + nums[i - 1]); } return Math.max(first[nums.length - 1], second[nums.length]); } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/linkedin/MergeKSortedLists.java
company/linkedin/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/linkedin/TwoSum.java
company/linkedin/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/linkedin/PalindromicSubstrings.java
company/linkedin/PalindromicSubstrings.java
//Given a string, your task is to count how many palindromic substrings in this string. //The substrings with different start indexes or end indexes are counted as different substrings //even they consist of same characters. //Example 1: //Input: "abc" //Output: 3 //Explanation: Three palindromic strings: "a", "b", "c". //Example 2: //Input: "aaa" //Output: 6 //Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa". //Note: //The input string length won't exceed 1000. class PalindromicSubstrings { int result = 0; public int countSubstrings(String s) { if(s == null || s.length() == 0) { return 0; } for(int i = 0; i < s.length(); i++) { extendPalindrome(s, i, i); extendPalindrome(s, i, i + 1); } return result; } public void extendPalindrome(String s, int left, int right) { while(left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) { result++; left--; right++; } } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/linkedin/MergeIntervals.java
company/linkedin/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/linkedin/SymmetricTree.java
company/linkedin/SymmetricTree.java
// Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). // For example, this binary tree [1,2,2,3,4,4,3] is symmetric: // 1 // / \ // 2 2 // / \ / \ // 3 4 4 3 // But the following [1,2,2,null,3,null,3] is not: // 1 // / \ // 2 2 // \ \ // 3 3 /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class SymmetricTree { public boolean isSymmetric(TreeNode root) { if(root == null) { return true; } return helper(root.left, root.right); } public boolean helper(TreeNode left, TreeNode right) { if(left == null && right == null) { return true; } if(left == null || right == null || left.val != right.val) { return false; } return helper(left.right, right.left) && helper(left.left, right.right); } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/linkedin/FindTheCelebrity.java
company/linkedin/FindTheCelebrity.java
// Suppose you are at a party with n people (labeled from 0 to n - 1) and among them, there may exist one celebrity. The definition of a celebrity is that all the other n - 1 people know him/her but he/she does not know any of them. // Now you want to find out who the celebrity is or verify that there is not one. The only thing you are allowed to do is to ask questions like: "Hi, A. Do you know B?" to get information of whether A knows B. You need to find out the celebrity (or verify there is not one) by asking as few questions as possible (in the asymptotic sense). // You are given a helper function bool knows(a, b) which tells you whether A knows B. Implement a function int findCelebrity(n), your function should minimize the number of calls to knows. // Note: There will be exactly one celebrity if he/she is in the party. Return the celebrity's label if there is a celebrity in the party. If there is no celebrity, return -1. /* The knows API is defined in the parent class Relation. boolean knows(int a, int b); */ public class FindTheCelebrity extends Relation { public int findCelebrity(int n) { //initialize candidate to 0 int candidate = 0; //find viable candidate for(int i = 1; i < n; i++) { if(knows(candidate, i)) { candidate = i; } } //check that everyone else knows the candidate for(int i = 0; i < n; i++) { //if the candidate knows the current person or the current person does not know the candidate, return -1 (candidate is not a celebrity) if(i != candidate && knows(candidate, i) || !knows(i, candidate)) { return -1; } } //return the celebrity return candidate; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/linkedin/MaximumDepthOfABinaryTree.java
company/linkedin/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/linkedin/MaximumProductSubarray.java
company/linkedin/MaximumProductSubarray.java
// Find the contiguous subarray within an array (containing at least one number) which has the largest product. // For example, given the array [2,3,-2,4], // the contiguous subarray [2,3] has the largest product = 6. public class MaximumProductSubarray { public int maxProduct(int[] nums) { if(nums == null || nums.length == 0) { return 0; } int result = nums[0]; int max = nums[0]; int min = nums[0]; for(int i = 1; i < nums.length; i++) { int temp = max; max = Math.max(Math.max(nums[i] * max, nums[i] * min), nums[i]); min = Math.min(Math.min(nums[i] * temp, nums[i] * min), nums[i]); if(max > result) { result = max; } } return result; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/linkedin/BinarySearchTreeIterator.java
company/linkedin/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/linkedin/ProductOfArrayExceptSelf.java
company/linkedin/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/linkedin/MinimumWindowSubstring.java
company/linkedin/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/linkedin/HouseRobber.java
company/linkedin/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/linkedin/InsertInterval.java
company/linkedin/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/linkedin/SparseMatrixMultiplication.java
company/linkedin/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/linkedin/Permutations.java
company/linkedin/Permutations.java
//Given a collection of distinct numbers, return all possible permutations. // //For example, //[1,2,3] have the following permutations: //[ //[1,2,3], //[1,3,2], //[2,1,3], //[2,3,1], //[3,1,2], //[3,2,1] //] class Permutations { public List<List<Integer>> permute(int[] nums) { LinkedList<List<Integer>> result = new LinkedList<List<Integer>>(); result.add(new ArrayList<Integer>()); for (int n: nums) { int size = result.size(); while(size > 0) { List<Integer> current = result.pollFirst(); for (int i = 0; i <= current.size(); i++) { List<Integer> temp = new ArrayList<Integer>(current); temp.add(i, n); result.add(temp); } size--; } } return result; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/linkedin/LowestCommonAncestorOfABinaryTree.java
company/linkedin/LowestCommonAncestorOfABinaryTree.java
// Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. // According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).” // _______3______ // / \ // ___5__ ___1__ // / \ / \ // 6 _2 0 8 // / \ // 7 4 // For example, the lowest common ancestor (LCA) of nodes 5 and 1 is 3. Another example is LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition. /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class LowestCommonAncestorOfABinaryTree { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if(root == null || root == p || root == q) { return root; } TreeNode left = lowestCommonAncestor(root.left, p, q); TreeNode right = lowestCommonAncestor(root.right, p, q); if(left != null && right != null) { return root; } return left == null ? right : left; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/linkedin/PowerOfXToTheN.java
company/linkedin/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/linkedin/MaximumSubarray.java
company/linkedin/MaximumSubarray.java
// Find the contiguous subarray within an array (containing at least one number) which has the largest sum. // For example, given the array [-2,1,-3,4,-1,2,1,-5,4], // the contiguous subarray [4,-1,2,1] has the largest sum = 6. public class MaximumSubarray { public int maxSubArray(int[] nums) { int[] dp = new int[nums.length]; dp[0] = nums[0]; int max = dp[0]; for(int i = 1; i < nums.length; i++) { dp[i] = nums[i] + (dp[i - 1] > 0 ? dp[i - 1] : 0); max = Math.max(dp[i], max); } return max; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/linkedin/PaintHouse.java
company/linkedin/PaintHouse.java
//There are a row of n houses, each house can be painted with one of the three colors: red, blue or green. //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 3 cost matrix. For example, //costs[0][0] is the cost of painting house 0 with color red; costs[1][2] is the cost of painting house 1 //with color green, and so on... Find the minimum cost to paint all houses. //Note: //All costs are positive integers. class PaintHouse { public int minCost(int[][] costs) { if(costs == null || costs.length == 0) { return 0; } for(int i = 1; i < costs.length; i++) { costs[i][0] += Math.min(costs[i - 1][1], costs[i - 1][2]); costs[i][1] += Math.min(costs[i - 1][0], costs[i - 1][2]); costs[i][2] += Math.min(costs[i - 1][0], costs[i - 1][1]); } return Math.min(Math.min(costs[costs.length - 1][0], costs[costs.length - 1][1]), costs[costs.length - 1][2]); } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/linkedin/BinaryTreeLevelOrderTraversal.java
company/linkedin/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/linkedin/SearchInRotatedSortedArray.java
company/linkedin/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/BinaryTreeVerticalOrderTraversal.java
company/facebook/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/facebook/HammingDistance.java
company/facebook/HammingDistance.java
// The Hamming distance between two integers is the number of positions at which the corresponding bits are different. // Given two integers x and y, calculate the Hamming distance. // Note: // 0 ≤ x, y < 2^31. // Example: // Input: x = 1, y = 4 // Output: 2 // Explanation: // 1 (0 0 0 1) // 4 (0 1 0 0) // ↑ ↑ // The above arrows point to positions where the corresponding bits are different. public class HammingDistance { public int hammingDistance(int x, int y) { return Integer.bitCount(x ^ y); } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/facebook/ExpressionAddOperators.java
company/facebook/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 ExpressionAddOperators { 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/facebook/KthLargestElementInAnArray.java
company/facebook/KthLargestElementInAnArray.java
// Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element. // For example, // Given [3,2,1,5,6,4] and k = 2, return 5. // Note: // You may assume k is always valid, 1 ≤ k ≤ array's length. public class KthLargestElementInAnArray { public int findKthLargest(int[] nums, int k) { int length = nums.length; Arrays.sort(nums); return nums[length - k]; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/facebook/CountAndSay.java
company/facebook/CountAndSay.java
// The count-and-say sequence is the sequence of integers beginning as follows: // 1, 11, 21, 1211, 111221, ... // 1 is read off as "one 1" or 11. // 11 is read off as "two 1s" or 21. // 21 is read off as "one 2, then one 1" or 1211. // Given an integer n, generate the nth sequence. // Note: The sequence of integers will be represented as a string. public class Solution { public String countAndSay(int n) { String s = "1"; for(int i = 1; i < n; i++) { s = helper(s); } return s; } public String helper(String s) { StringBuilder sb = new StringBuilder(); char c = s.charAt(0); int count = 1; for(int i = 1; i < s.length(); i++) { if(s.charAt(i) == c) count++; else { sb.append(count); sb.append(c); c = s.charAt(i); count = 1; } } sb.append(count); sb.append(c); return sb.toString(); } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/facebook/NumberOfIslands.java
company/facebook/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/facebook/ReverseLinkedList.java
company/facebook/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/facebook/DecodeWays.java
company/facebook/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/facebook/MergeKSortedLists.java
company/facebook/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/facebook/AddAndSearchWordDataStructureDesign.java
company/facebook/AddAndSearchWordDataStructureDesign.java
// Design a data structure that supports the following two operations: // void addWord(word) // bool search(word) // search(word) can search a literal word or a regular expression string containing only letters a-z or .. A . means it can represent any one letter. // For example: // addWord("bad") // addWord("dad") // addWord("mad") // search("pad") -> false // search("bad") -> true // search(".ad") -> true // search("b..") -> true // Note: // You may assume that all words are consist of lowercase letters a-z. public class AddAndSearchWordDataStructure { public class TrieNode { public TrieNode[] children = new TrieNode[26]; public String item = ""; } private TrieNode root = new TrieNode(); public void addWord(String word) { TrieNode node = root; for (char c : word.toCharArray()) { if (node.children[c - 'a'] == null) { node.children[c - 'a'] = new TrieNode(); } node = node.children[c - 'a']; } node.item = word; } public boolean search(String word) { return match(word.toCharArray(), 0, root); } private boolean match(char[] chs, int k, TrieNode node) { if (k == chs.length) { return !node.item.equals(""); } if (chs[k] != '.') { return node.children[chs[k] - 'a'] != null && match(chs, k + 1, node.children[chs[k] - 'a']); } else { for (int i = 0; i < node.children.length; i++) { if (node.children[i] != null) { if (match(chs, k + 1, node.children[i])) { return true; } } } } return false; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/facebook/EncodeAndDecodeTinyURL.java
company/facebook/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/facebook/OneEditDistance.java
company/facebook/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/facebook/ImplementTrie.java
company/facebook/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/facebook/MoveZeros.java
company/facebook/MoveZeros.java
// Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. // For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0]. // Note: // You must do this in-place without making a copy of the array. // Minimize the total number of operations. public class MoveZeros { public void moveZeroes(int[] nums) { if(nums == null || nums.length == 0) { return; } int index = 0; for(int num : nums) { if(num != 0) { nums[index] = num; index++; } } while(index < nums.length) { nums[index] = 0; index++; } } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/facebook/TwoSum.java
company/facebook/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/facebook/MinimumSizeSubarraySum.java
company/facebook/MinimumSizeSubarraySum.java
// Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ≥ s. If there isn't one, return 0 instead. // For example, given the array [2,3,1,2,4,3] and s = 7, // the subarray [4,3] has the minimal length under the problem constraint. public class MinimumSizeSubarraySum { public int minSubArrayLen(int s, int[] nums) { if(nums == null || nums.length == 0) { return 0; } int i = 0; int j = 0; int result = Integer.MAX_VALUE; int total = 0; while(i < nums.length) { total += nums[i++]; while(total >= s) { result = Math.min(result, i - j); total -= nums[j++]; } } return result == Integer.MAX_VALUE ? 0 : result; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/facebook/PalindromicSubstrings.java
company/facebook/PalindromicSubstrings.java
//Given a string, your task is to count how many palindromic substrings in this string. //The substrings with different start indexes or end indexes are counted as different substrings //even they consist of same characters. //Example 1: //Input: "abc" //Output: 3 //Explanation: Three palindromic strings: "a", "b", "c". //Example 2: //Input: "aaa" //Output: 6 //Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa". //Note: //The input string length won't exceed 1000. class PalindromicSubstrings { int result = 0; public int countSubstrings(String s) { if(s == null || s.length() == 0) { return 0; } for(int i = 0; i < s.length(); i++) { extendPalindrome(s, i, i); extendPalindrome(s, i, i + 1); } return result; } public void extendPalindrome(String s, int left, int right) { while(left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) { result++; left--; right++; } } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/facebook/CloneGraph.java
company/facebook/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/facebook/InorderSuccessorInBST.java
company/facebook/InorderSuccessorInBST.java
// Given a binary search tree and a node in it, find the in-order successor of that node in the BST. // Note: If the given node has no in-order successor in the tree, return null. /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class InorderSuccessorInBST { public TreeNode inorderSuccessor(TreeNode root, TreeNode p) { TreeNode successor = null; while(root != null) { if(p.val < root.val) { successor = root; root = root.left; } else { root = root.right; } } return successor; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/facebook/IntegerToEnglishWords.java
company/facebook/IntegerToEnglishWords.java
// Convert a non-negative integer to its english words representation. Given input is guaranteed to be less than 231 - 1. // For example, // 123 -> "One Hundred Twenty Three" // 12345 -> "Twelve Thousand Three Hundred Forty Five" // 1234567 -> "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven" public class IntegerToEnglishWords { private final String[] LESS_THAN_20 = { "", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen" }; private final String[] TENS = { "", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety" }; private final String[] THOUSANDS = { "", "Thousand", "Million", "Billion" }; public String numberToWords(int num) { if(num == 0) { return "Zero"; } int i = 0; String words = ""; while(num > 0) { if(num % 1000 != 0) { words = helper(num % 1000) + THOUSANDS[i] + " " + words; } num /= 1000; i++; } return words.trim(); } private String helper(int num) { if(num == 0) { return ""; } else if(num < 20) { return LESS_THAN_20[num] + " "; } else if(num < 100) { return TENS[num / 10] + " " + helper(num % 10); } else { return LESS_THAN_20[num / 100] + " Hundred " + helper(num % 100); } } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/facebook/MergeIntervals.java
company/facebook/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/facebook/MergeSortedArray.java
company/facebook/MergeSortedArray.java
// Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. // Note: // You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. The number of elements initialized in nums1 and nums2 are m and n respectively. public class MergeSortedArray { public void merge(int[] A, int m, int[] B, int n) { int i = m - 1; int j = n - 1; int k = m + n - 1; while(i >= 0 && j >= 0) { A[k--] = A[i] > B[j] ? A[i--] : B[j--]; } while(j >= 0) { A[k--] = B[j--]; } } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/facebook/3Sum.java
company/facebook/3Sum.java
// Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. // Note: The solution set must not contain duplicate triplets. // For example, given array S = [-1, 0, 1, 2, -1, -4], // A solution set is: // [ // [-1, 0, 1], // [-1, -1, 2] // ] public class 3Sum { public List<List<Integer>> threeSum(int[] nums) { List<List<Integer>> result = new ArrayList<>(); Arrays.sort(nums); for(int i = 0; i < nums.length - 2; i++) { if(i > 0 && nums[i] == nums[i - 1]) { continue; } int j = i + 1; int k = nums.length - 1; int target = -nums[i]; while(j < k) { if(nums[j] + nums[k] == target) { ArrayList<Integer> temp = new ArrayList<Integer>(); temp.add(nums[i]); temp.add(nums[j]); temp.add(nums[k]); result.add(temp); j++; k--; while(j < k && nums[j] == nums[j - 1]) { j++; } while(j < k && nums[k] == nums[k + 1]) { k--; } } else if(nums[j] + nums[k] > target) { k--; } else { j++; } } } return result; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/facebook/LetterCombinationsOfAPhoneNumber.java
company/facebook/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/facebook/MultiplyStrings.java
company/facebook/MultiplyStrings.java
// Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2. // Note: // The length of both num1 and num2 is < 110. // Both num1 and num2 contains only digits 0-9. // Both num1 and num2 does not contain any leading zero. // You must not use any built-in BigInteger library or convert the inputs to integer directly. public class MultiplyStrings { public String multiply(String num1, String num2) { int m = num1.length(); int n = num2.length(); int[] pos = new int[m + n]; for(int i = m - 1; i >= 0; i--) { for(int j = n - 1; j >= 0; j--) { int mul = (num1.charAt(i) - '0') * (num2.charAt(j) - '0'); int p1 = i + j; int p2 = i + j + 1; int sum = mul + pos[p2]; pos[p1] += sum / 10; pos[p2] = (sum) % 10; } } StringBuilder sb = new StringBuilder(); for(int p : pos) { if(!(sb.length() == 0 && p == 0)) { sb.append(p); } } return sb.length() == 0 ? "0" : sb.toString(); } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/facebook/FindTheCelebrity.java
company/facebook/FindTheCelebrity.java
// Suppose you are at a party with n people (labeled from 0 to n - 1) and among them, there may exist one celebrity. The definition of a celebrity is that all the other n - 1 people know him/her but he/she does not know any of them. // Now you want to find out who the celebrity is or verify that there is not one. The only thing you are allowed to do is to ask questions like: "Hi, A. Do you know B?" to get information of whether A knows B. You need to find out the celebrity (or verify there is not one) by asking as few questions as possible (in the asymptotic sense). // You are given a helper function bool knows(a, b) which tells you whether A knows B. Implement a function int findCelebrity(n), your function should minimize the number of calls to knows. // Note: There will be exactly one celebrity if he/she is in the party. Return the celebrity's label if there is a celebrity in the party. If there is no celebrity, return -1. /* The knows API is defined in the parent class Relation. boolean knows(int a, int b); */ public class FindTheCelebrity extends Relation { public int findCelebrity(int n) { //initialize candidate to 0 int candidate = 0; //find viable candidate for(int i = 1; i < n; i++) { if(knows(candidate, i)) { candidate = i; } } //check that everyone else knows the candidate for(int i = 0; i < n; i++) { //if the candidate knows the current person or the current person does not know the candidate, return -1 (candidate is not a celebrity) if(i != candidate && knows(candidate, i) || !knows(i, candidate)) { return -1; } } //return the celebrity return candidate; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/facebook/BestTimeToBuyAndSellStock.java
company/facebook/BestTimeToBuyAndSellStock.java
// Say you have an array for which the ith element is the price of a given stock on day i. // If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit. // Example 1: // Input: [7, 1, 5, 3, 6, 4] // Output: 5 // max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price) // Example 2: // Input: [7, 6, 4, 3, 1] // Output: 0 // In this case, no transaction is done, i.e. max profit = 0. public class BestTimeToBuyAndSellStock { public int maxProfit(int[] prices) { //Kadane's algorithm if(prices.length == 0) { return 0; } int max = 0; int min = prices[0]; for(int i = 1; i < prices.length; i++) { if(prices[i] > min) { max = Math.max(max, prices[i] - min); } else { min = prices[i]; } } return max; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/facebook/MinStack.java
company/facebook/MinStack.java
/** * 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/facebook/RegularExpressionMatching.java
company/facebook/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/facebook/MaximumSizeSubarraySumEqualsK.java
company/facebook/MaximumSizeSubarraySumEqualsK.java
// Given an array nums and a target value k, find the maximum length of a subarray that sums to k. If there isn't one, return 0 instead. // Note: // The sum of the entire nums array is guaranteed to fit within the 32-bit signed integer range. // Example 1: // Given nums = [1, -1, 5, -2, 3], k = 3, // return 4. (because the subarray [1, -1, 5, -2] sums to 3 and is the longest) // Example 2: // Given nums = [-2, -1, 2, 1], k = 1, // return 2. (because the subarray [-1, 2] sums to 1 and is the longest) // Follow Up: // Can you do it in O(n) time? public class MaximumSizeSubarraySumEqualsK { public int maxSubArrayLen(int[] nums, int k) { if(nums.length == 0) { return 0; } HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); int maxLength = 0; int total = 0; map.put(0, -1); for(int i = 0; i < nums.length; i++) { total += nums[i]; if(map.containsKey(total - k)) { maxLength = Math.max(maxLength, i - map.get(total - k)); } if(!map.containsKey(total)) { map.put(total, i); } } return maxLength; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/company/facebook/InsertDeleteGetRandomO1.java
company/facebook/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