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/bit-manipulation/MaximumProductOfWordLengths.java
leetcode/bit-manipulation/MaximumProductOfWordLengths.java
// Given a string array words, find the maximum value of length(word[i]) * length(word[j]) where the two words do not share common letters. You may assume that each word will contain only lower case letters. If no such two words exist, return 0. // Example 1: // Given ["abcw", "baz", "foo", "bar", "xtfn", "abcdef"] // Return 16 // The two words can be "abcw", "xtfn". // Example 2: // Given ["a", "ab", "abc", "d", "cd", "bcd", "abcd"] // Return 4 // The two words can be "ab", "cd". // Example 3: // Given ["a", "aa", "aaa", "aaaa"] // Return 0 // No such pair of words. public class MaximumProductOfWordLengths { public int maxProduct(String[] words) { if(words.length == 0 || words == null) { return 0; } int length = words.length; int[] value = new int[length]; int max = 0; for(int i = 0; i < length; i++) { String temp = words[i]; value[i] = 0; for(int j = 0; j < temp.length(); j++) { value[i] |= 1 << (temp.charAt(j) - 'a'); } } for(int i = 0; i < length; i++) { for(int j = 1; j < length; j++) { if((value[i] & value[j]) == 0 && (words[i].length() * words[j].length()) > max) { max = words[i].length() * words[j].length(); } } } return max; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/bit-manipulation/NumberOfOneBits.java
leetcode/bit-manipulation/NumberOfOneBits.java
// Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight). // For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so the function should return 3. public class NumberOfOneBits { // you need to treat n as an unsigned value public int hammingWeight(int n) { if(n == 0) { return 0; } int count = 0; while(n != 0) { count += (n) & 1; n >>>= 1; } return count; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/bit-manipulation/PowerOfTwo.java
leetcode/bit-manipulation/PowerOfTwo.java
//Given an integer, write a function to determine if it is a power of two. // //Example 1: // //Input: 1 //Output: true //Example 2: // //Input: 16 //Output: true //Example 3: // //Input: 218 //Output: false class PowerOfTwo { public boolean isPowerOfTwo(int n) { long i = 1; while(i < n) { i <<= 1; } return i == n; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/bit-manipulation/SumOfTwoInteger.java
leetcode/bit-manipulation/SumOfTwoInteger.java
// Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -. // Example: // Given a = 1 and b = 2, return 3. public class SumOfTwoIntegers { public int getSum(int a, int b) { if(a == 0) { return b; } if(b == 0) { return a; } while(b != 0) { int carry = a & b; a = a ^ b; b = carry << 1; } return a; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/bit-manipulation/BinaryWatch.java
leetcode/bit-manipulation/BinaryWatch.java
// A binary watch has 4 LEDs on the top which represent the hours (0-11), and the 6 LEDs on the bottom represent the minutes (0-59). // Each LED represents a zero or one, with the least significant bit on the right. // For example, the above binary watch reads "3:25". // Given a non-negative integer n which represents the number of LEDs that are currently on, return all possible times the watch could represent. // Example: // Input: n = 1 // Return: ["1:00", "2:00", "4:00", "8:00", "0:01", "0:02", "0:04", "0:08", "0:16", "0:32"] // Note: // The order of output does not matter. // The hour must not contain a leading zero, for example "01:00" is not valid, it should be "1:00". // The minute must be consist of two digits and may contain a leading zero, for example "10:2" is not valid, it should be "10:02". public class BinaryWatch { public List<String> readBinaryWatch(int num) { ArrayList<String> allTimes = new ArrayList<String>(); //iterate through all possible time combinations for(int i = 0; i < 12; i++) { for(int j = 0; j < 60; j++) { //if the current number and n have the same number of bits the time is possible if(Integer.bitCount(i * 64 + j) == num) { //add the current time to all times arraylist allTimes.add(String.format("%d:%02d", i, j)); } } } return allTimes; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/bit-manipulation/Utf8Validation.java
leetcode/bit-manipulation/Utf8Validation.java
// A character in UTF8 can be from 1 to 4 bytes long, subjected to the following rules: // For 1-byte character, the first bit is a 0, followed by its unicode code. // For n-bytes character, the first n-bits are all one's, the n+1 bit is 0, followed by n-1 bytes with most significant 2 bits being 10. // This is how the UTF-8 encoding would work: // Char. number range | UTF-8 octet sequence // (hexadecimal) | (binary) // --------------------+--------------------------------------------- // 0000 0000-0000 007F | 0xxxxxxx // 0000 0080-0000 07FF | 110xxxxx 10xxxxxx // 0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx // 0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx // Given an array of integers representing the data, return whether it is a valid utf-8 encoding. // Note: // The input is an array of integers. Only the least significant 8 bits of each integer is used to store the data. This means each integer represents only 1 byte of data. // Example 1: // data = [197, 130, 1], which represents the octet sequence: 11000101 10000010 00000001. // Return true. // It is a valid utf-8 encoding for a 2-bytes character followed by a 1-byte character. // Example 2: // data = [235, 140, 4], which represented the octet sequence: 11101011 10001100 00000100. // Return false. // The first 3 bits are all one's and the 4th bit is 0 means it is a 3-bytes character. // The next byte is a continuation byte which starts with 10 and that's correct. // But the second continuation byte does not start with 10, so it is invalid. public class Utf8Validation { public boolean validUtf8(int[] data) { int count = 0; for(int i : data) { if(count == 0) { if((i >> 5) == 0b110) { count = 1; } else if((i >> 4) == 0b1110) { count = 2; } else if((i >> 3) == 0b11110) { count = 3; } else if((i >> 7) == 0b1) { return false; } } else { if((i >> 6) != 0b10) { return false; } count--; } } return count == 0; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/divide-and-conquer/ExpressionAddOperators.java
leetcode/divide-and-conquer/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/leetcode/divide-and-conquer/KthLargestElementInAnArray.java
leetcode/divide-and-conquer/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/leetcode/stack/DailyTemperatures.java
leetcode/stack/DailyTemperatures.java
//Given a list of daily temperatures, produce a list that, for each day in the input, tells you how many days you would have to wait until a warmer temperature. If there is no future day for which this is possible, put 0 instead. // //For example, given the list temperatures = [73, 74, 75, 71, 69, 72, 76, 73], your output should be [1, 1, 4, 2, 1, 1, 0, 0]. // //Note: The length of temperatures will be in the range [1, 30000]. Each temperature will be an integer in the range [30, 100]. class DailyTemperatures { public int[] dailyTemperatures(int[] temperatures) { int[] result = new int[temperatures.length]; Stack<Integer> stack = new Stack<Integer>(); for(int i = 0; i < temperatures.length; i++) { while(!stack.isEmpty() && temperatures[i] > temperatures[stack.peek()]) { int index = stack.pop(); result[index] = i - index; } stack.push(i); } return result; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/stack/MinStack.java
leetcode/stack/MinStack.java
//Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. //push(x) -- Push element x onto stack. //pop() -- Removes the element on top of the stack. //top() -- Get the top element. //getMin() -- Retrieve the minimum element in the stack. /** * Your MinStack object will be instantiated and called as such: * MinStack obj = new MinStack(); * obj.push(x); * obj.pop(); * int param_3 = obj.top(); * int param_4 = obj.getMin(); */ class MinStack { class Node { int data; int min; Node next; public Node(int data, int min) { this.data = data; this.min = min; this.next = null; } } Node head; /** initialize your data structure here. */ public MinStack() { } public void push(int x) { if(head == null) { head = new Node(x, x); } else { Node newNode = new Node(x, Math.min(x, head.min)); newNode.next = head; head = newNode; } } public void pop() { head = head.next; } public int top() { return head.data; } public int getMin() { return head.min; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/stack/BinarySearchTreeIterator.java
leetcode/stack/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/leetcode/stack/DecodeString.java
leetcode/stack/DecodeString.java
// Given an encoded string, return it's decoded string. // The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer. // You may assume that the input string is always valid; No extra white spaces, square brackets are well-formed, etc. // Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there won't be input like 3a or 2[4]. public class DecodeString { public String decodeString(String s) { //declare empty string String decoded = ""; //initialize stack to hold counts Stack<Integer> countStack = new Stack<Integer>(); //initalize stack to hold decoded string Stack<String> decodedStack = new Stack<String>(); //initialize index to zero int index = 0; //iterate through entire string while(index < s.length()) { //if the current character is numeric... if(Character.isDigit(s.charAt(index))) { int count = 0; //determine the number while(Character.isDigit(s.charAt(index))) { count = 10 * count + (s.charAt(index) - '0'); index++; } //push the number onto the count stack countStack.push(count); } else if(s.charAt(index) == '[') { //if the current character is an opening bracket decodedStack.push(decoded); decoded = ""; index++; } else if(s.charAt(index) == ']') { //if the current character is a closing bracket StringBuilder temp = new StringBuilder(decodedStack.pop()); int repeatTimes = countStack.pop(); for(int i = 0; i < repeatTimes; i++) { temp.append(decoded); } decoded = temp.toString(); index++; } else { //otherwise, append the current character to the decoded string decoded += s.charAt(index); index++; } } //return the decoded string return decoded; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/stack/FlattenNestedListIterator.java
leetcode/stack/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/leetcode/stack/TrappingRainWater.java
leetcode/stack/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/leetcode/stack/ExclusiveTimeOfFunctions.java
leetcode/stack/ExclusiveTimeOfFunctions.java
//Given the running logs of n functions that are executed in a nonpreemptive single threaded CPU, find the exclusive time of these functions. //Each function has a unique id, start from 0 to n-1. A function may be called recursively or by another function. //A log is a string has this format : function_id:start_or_end:timestamp. For example, "0:start:0" means function 0 starts from the very beginning of time 0. "0:end:0" means function 0 ends to the very end of time 0. //Exclusive time of a function is defined as the time spent within this function, the time spent by calling other functions should not be considered as this function's exclusive time. You should return the exclusive time of each function sorted by their function id. //Example 1: //Input: //n = 2 //logs = //["0:start:0", //"1:start:2", //"1:end:5", //"0:end:6"] //Output:[3, 4] //Explanation: //Function 0 starts at time 0, then it executes 2 units of time and reaches the end of time 1. //Now function 0 calls function 1, function 1 starts at time 2, executes 4 units of time and end at time 5. //Function 0 is running again at time 6, and also end at the time 6, thus executes 1 unit of time. //So function 0 totally execute 2 + 1 = 3 units of time, and function 1 totally execute 4 units of time. //Note: //Input logs will be sorted by timestamp, NOT log id. //Your output should be sorted by function id, which means the 0th element of your output corresponds to the exclusive time of function 0. //Two functions won't start or end at the same time. //Functions could be called recursively, and will always end. //1 <= n <= 100 class ExclusiveTimeOfFunctions { public int[] exclusiveTime(int n, List<String> logs) { Stack<Integer> stack = new Stack <Integer>(); int[] result = new int[n]; String[] current = logs.get(0).split(":"); stack.push(Integer.parseInt(current[0])); int i = 1; int previous = Integer.parseInt(current[2]); while (i < logs.size()) { current = logs.get(i).split(":"); if (current[1].equals("start")) { if (!stack.isEmpty()) { result[stack.peek()] += Integer.parseInt(current[2]) - previous; } stack.push(Integer.parseInt(current[0])); previous = Integer.parseInt(current[2]); } else { result[stack.peek()] += Integer.parseInt(current[2]) - previous + 1; stack.pop(); previous = Integer.parseInt(current[2]) + 1; } i++; } return result; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/queue/MovingAverageFromDataStream.java
leetcode/queue/MovingAverageFromDataStream.java
// Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window. // For example, // MovingAverage m = new MovingAverage(3); // m.next(1) = 1 // m.next(10) = (1 + 10) / 2 // m.next(3) = (1 + 10 + 3) / 3 // m.next(5) = (10 + 3 + 5) / 3 /** * Your MovingAverage object will be instantiated and called as such: * MovingAverage obj = new MovingAverage(size); * double param_1 = obj.next(val); */ public class MovingAverageFromDataStream { double previousSum = 0.0; int maxSize; Queue<Integer> window; /** Initialize your data structure here. */ public MovingAverage(int size) { this.maxSize = size; window = new LinkedList<Integer>(); } public double next(int val) { if(window.size() == maxSize) { previousSum -= window.remove(); } window.add(val); previousSum += val; return previousSum / window.size(); } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/brainteaser/BulbSwitcher.java
leetcode/brainteaser/BulbSwitcher.java
//There are n bulbs that are initially off. You first turn on all the bulbs. Then, you turn off every second bulb. On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For the ith round, you toggle every i bulb. For the nth round, you only toggle the last bulb. Find how many bulbs are on after n rounds. //Example: //Given n = 3. //At first, the three bulbs are [off, off, off]. //After first round, the three bulbs are [on, on, on]. //After second round, the three bulbs are [on, off, on]. //After third round, the three bulbs are [on, off, off]. //So you should return 1, because there is only one bulb is on. class BulbSwitcher { public int bulbSwitch(int n) { return (int)Math.sqrt(n); } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/two-pointers/LinkedListCycle.java
leetcode/two-pointers/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/leetcode/two-pointers/MoveZeros.java
leetcode/two-pointers/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/leetcode/two-pointers/MinimumSizeSubarraySum.java
leetcode/two-pointers/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/leetcode/two-pointers/MergeSortedArray.java
leetcode/two-pointers/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/leetcode/two-pointers/3Sum.java
leetcode/two-pointers/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/leetcode/two-pointers/3SumSmaller.java
leetcode/two-pointers/3SumSmaller.java
// Given an array of n integers nums and a target, find the number of index triplets i, j, k with 0 <= i < j < k < n that satisfy the condition nums[i] + nums[j] + nums[k] < target. // For example, given nums = [-2, 0, 1, 3], and target = 2. // Return 2. Because there are two triplets which sums are less than 2: // [-2, 0, 1] // [-2, 0, 3] // Follow up: // Could you solve it in O(n2) runtime? public class 3SumSmaller { public int threeSumSmaller(int[] nums, int target) { //initialize total count to zero int count = 0; //sort the array Arrays.sort(nums); //loop through entire array for(int i = 0; i < nums.length - 2; i++) { //set left to i + 1 int left = i + 1; //set right to end of array int right = nums.length - 1; //while left index < right index while(left < right) { //if the 3 indices add to less than the target increment count if(nums[i] + nums[left] + nums[right] < target) { //increment the count by the distance between left and right because the array is sorted count += right - left; //decrement right pointer left++; } else { //if they sum to a value greater than target... //increment left pointer right--; } } } return count; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/two-pointers/RemoveElement.java
leetcode/two-pointers/RemoveElement.java
//Given an array and a value, remove all instances of that value in-place and return the new length. //Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. //The order of elements can be changed. It doesn't matter what you leave beyond the new length. //Example: //Given nums = [3,2,2,3], val = 3, //Your function should return length = 2, with the first two elements of nums being 2. class RemoveElement { public int removeElement(int[] nums, int val) { int index = 0; for(int i = 0; i < nums.length; i++) { if(nums[i] != val) { nums[index++] = nums[i]; } } return index; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/two-pointers/RemoveDuplicatesFromSortedArray.java
leetcode/two-pointers/RemoveDuplicatesFromSortedArray.java
// Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length. // Do not allocate extra space for another array, you must do this in place with constant memory. // For example, // Given input array nums = [1,1,2], // Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn't matter what you leave beyond the new length. public class RemoveDuplicatesFromSortedArray { public int removeDuplicates(int[] nums) { if(nums.length == 0 || nums == null) { return 0; } if(nums.length < 2) { return nums.length; } int index = 1; for(int i = 1; i < nums.length; i++) { if(nums[i] != nums[i - 1]) { nums[index++] = nums[i]; } } return index; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/two-pointers/SortColors.java
leetcode/two-pointers/SortColors.java
// Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue. // Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. // Note: // You are not suppose to use the library's sort function for this problem. public class SortColors { public void sortColors(int[] nums) { int wall = 0; for(int i = 0; i < nums.length; i++) { if(nums[i] < 1) { int temp = nums[i]; nums[i] = nums[wall]; nums[wall] = temp; wall++; } } for(int i = 0; i < nums.length; i++) { if(nums[i] == 1) { int temp = nums[i]; nums[i] = nums[wall]; nums[wall] = temp; wall++; } } } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/two-pointers/ReverseString.java
leetcode/two-pointers/ReverseString.java
// Write a function that takes a string as input and returns the string reversed. // Example: // Given s = "hello", return "olleh". public class ReverseString { public String reverseString(String s) { if(s == null || s.length() == 1 || s.length() == 0) { return s; } char[] word = s.toCharArray(); for(int i = 0, j = s.length() - 1; i < j; i++, j--) { char temp = word[i]; word[i] = word[j]; word[j] = temp; } return new String(word); } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/depth-first-search/NumberOfIslands.java
leetcode/depth-first-search/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/leetcode/depth-first-search/BattleshipsInABoard.java
leetcode/depth-first-search/BattleshipsInABoard.java
// Given an 2D board, count how many battleships are in it. The battleships are represented with 'X's, empty slots are represented with '.'s. You may assume the following rules: // You receive a valid board, made of only battleships or empty slots. // Battleships can only be placed horizontally or vertically. In other words, they can only be made of the shape 1xN (1 row, N columns) or Nx1 (N rows, 1 column), where N can be of any size. // At least one horizontal or vertical cell separates between two battleships - there are no adjacent battleships. // Example: // X..X // ...X // ...X // In the above board there are 2 battleships. // Invalid Example: // ...X // XXXX // ...X // This is an invalid board that you will not receive - as battleships will always have a cell separating between them. // Follow up: // Could you do it in one-pass, using only O(1) extra memory and without modifying the value of the board? public class BattleshipsInABoard { public int countBattleships(char[][] board) { int ships = 0; for(int i = 0; i < board.length; i++) { for(int j = 0; j < board[0].length; j++) { if(board[i][j] == 'X') { ships++; sink(board, i, j, 1); } } } return ships; } public void sink(char[][] board, int i, int j, int numberOfShips) { if(i < 0 || i >= board.length || j < 0 || j >= board[0].length || board[i][j] == '.') { return; } board[i][j] = '.'; sink(board, i + 1, j, numberOfShips + 1); sink(board, i, j + 1, numberOfShips + 1); } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/depth-first-search/MaximumDepthOfABinaryTree.java
leetcode/depth-first-search/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/leetcode/depth-first-search/BalancedBinaryTree.java
leetcode/depth-first-search/BalancedBinaryTree.java
// Given a binary tree, determine if it is height-balanced. // For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1. /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class BalancedBinaryTree { boolean balanced = true; public boolean isBalanced(TreeNode root) { height(root); return balanced; } private int height(TreeNode root) { if(root == null) { return 0; } int leftHeight = height(root.left); int rightHeight = height(root.right); if(Math.abs(leftHeight - rightHeight) > 1) { balanced = false; } return 1 + Math.max(leftHeight, rightHeight); } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/depth-first-search/SameTree.java
leetcode/depth-first-search/SameTree.java
// Given two binary trees, write a function to check if they are equal or not. // Two binary trees are considered equal if they are structurally identical and the nodes have the same value. /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class SameTree { public boolean isSameTree(TreeNode p, TreeNode q) { if(p == null && q == null) { return true; } if(p == null && q != null || q == null && p != null) { return false; } if(p.val != q.val) { return false; } return isSameTree(p.left, q.left) && isSameTree(p.right, q.right); } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/depth-first-search/ConvertSortedArrayToBinarySearchTree.java
leetcode/depth-first-search/ConvertSortedArrayToBinarySearchTree.java
// Given an array where elements are sorted in ascending order, convert it to a height balanced BST. /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class ConvertSortedArrayToBinarySearchTree { public TreeNode sortedArrayToBST(int[] nums) { if(nums.length == 0) { return null; } TreeNode root = helper(nums, 0, nums.length - 1); return root; } private TreeNode helper(int[] nums, int start, int end) { if(start <= end) { int mid = (start + end) / 2; TreeNode current = new TreeNode(nums[mid]); current.left = helper(nums, start, mid - 1); current.right = helper(nums, mid + 1, end); return current; } return null; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/depth-first-search/PopulatingNextRightPointersInEachNode.java
leetcode/depth-first-search/PopulatingNextRightPointersInEachNode.java
// Given a binary tree // struct TreeLinkNode { // TreeLinkNode *left; // TreeLinkNode *right; // TreeLinkNode *next; // } // Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL. // Initially, all next pointers are set to NULL. // Note: // You may only use constant extra space. // You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children). // For example, // Given the following perfect binary tree, // 1 // / \ // 2 3 // / \ / \ // 4 5 6 7 // After calling your function, the tree should look like: // 1 -> NULL // / \ // 2 -> 3 -> NULL // / \ / \ // 4->5->6->7 -> NULL /** * Definition for binary tree with next pointer. * public class TreeLinkNode { * int val; * TreeLinkNode left, right, next; * TreeLinkNode(int x) { val = x; } * } */ public class PopulatingNextRightPointersInEachNode { public void connect(TreeLinkNode root) { if(root == null) { return; } Queue<TreeLinkNode> queue = new LinkedList<TreeLinkNode>(); queue.add(root); while(!queue.isEmpty()) { Queue<TreeLinkNode> currentLevel = new LinkedList<TreeLinkNode>(); TreeLinkNode temp = null; while(!queue.isEmpty()) { TreeLinkNode current = queue.remove(); current.next = temp; temp = current; if(current.right != null) { currentLevel.add(current.right); } if(current.left!= null) { currentLevel.add(current.left); } } queue = currentLevel; } } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/array/MinCostClimbingStairs.java
leetcode/array/MinCostClimbingStairs.java
//On a staircase, the i-th step has some non-negative cost cost[i] assigned (0 indexed). // //Once you pay the cost, you can either climb one or two steps. You need to find minimum cost to reach the top of the floor, and you can either start from the step with index 0, or the step with index 1. // //Example 1: //Input: cost = [10, 15, 20] //Output: 15 //Explanation: Cheapest is start on cost[1], pay that cost and go to the top. //Example 2: //Input: cost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1] //Output: 6 //Explanation: Cheapest is start on cost[0], and only step on 1s, skipping cost[3]. //Note: //cost will have a length in the range [2, 1000]. //Every cost[i] will be an integer in the range [0, 999]. class MinCostClimbingStairs { public int minCostClimbingStairs(int[] cost) { if(cost == null || cost.length == 0) { return 0; } if(cost.length == 1) { return cost[0]; } if(cost.length == 2) { return Math.min(cost[0], cost[1]); } int[] dp = new int[cost.length]; dp[0] = cost[0]; dp[1] = cost[1]; for(int i = 2; i < cost.length; i++) { dp[i] = Math.min(dp[i - 1] + cost[i], dp[i - 2] + cost[i]); } return Math.min(dp[cost.length - 1], dp[cost.length -2]); } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/array/PlusOne.java
leetcode/array/PlusOne.java
//Given a non-empty array of digits representing a non-negative integer, plus one to the integer. // //The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit. // //You may assume the integer does not contain any leading zero, except the number 0 itself. // //Example 1: // //Input: [1,2,3] //Output: [1,2,4] //Explanation: The array represents the integer 123. //Example 2: // //Input: [4,3,2,1] //Output: [4,3,2,2] //Explanation: The array represents the integer 4321. class Solution { public int[] plusOne(int[] digits) { for(int i = digits.length - 1; i >= 0; i--) { if(digits[i] < 9) { digits[i]++; return digits; } digits[i] = 0; } int[] result = new int[digits.length + 1]; result[0] = 1; return result; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/array/MergeIntervals.java
leetcode/array/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/leetcode/array/UniquePaths.java
leetcode/array/UniquePaths.java
//A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). // //The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). // //How many possible unique paths are there? class UniquePaths { public int uniquePaths(int m, int n) { Integer[][] map = new Integer[m][n]; //only 1 way to get to ith row, 0th column (move down) for(int i = 0; i < m; i++){ map[i][0] = 1; } //only 1 way to get to ith column, 0th row (move right) for(int j= 0; j < n; j++){ map[0][j]=1; } //x ways to get to ith row, jth column (# of ways to get to //ith - 1 row, jth column + # of ways to get to jth - 1 column //ith column for(int i = 1;i < m; i++){ for(int j = 1; j < n; j++){ map[i][j] = map[i - 1][j] + map[i][j - 1]; } } return map[m - 1][n - 1]; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/array/ContainsDuplicatesII.java
leetcode/array/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/leetcode/array/FindTheCelebrity.java
leetcode/array/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/leetcode/array/BestTimeToBuyAndSellStock.java
leetcode/array/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 min = prices[0]; int max = 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/leetcode/array/SpiralMatrixII.java
leetcode/array/SpiralMatrixII.java
// Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. // For example, // Given n = 3, // You should return the following matrix: // [ // [ 1, 2, 3 ], // [ 8, 9, 4 ], // [ 7, 6, 5 ] // ] public class SpiralMatrix { public int[][] generateMatrix(int n) { int[][] spiral = new int[n][n]; if(n == 0) { return spiral; } int rowStart = 0; int colStart = 0; int rowEnd = n - 1; int colEnd = n -1; int number = 1; while(rowStart <= rowEnd && colStart <= colEnd) { for(int i = colStart; i <= colEnd; i++) { spiral[rowStart][i] = number++; } rowStart++; for(int i = rowStart; i <= rowEnd; i++) { spiral[i][colEnd] = number++; } colEnd--; for(int i = colEnd; i >= colStart; i--) { if(rowStart <= rowEnd) { spiral[rowEnd][i] = number++; } } rowEnd--; for(int i = rowEnd; i >= rowStart; i--) { if(colStart <= colEnd) { spiral[i][colStart] = number++; } } colStart++; } return spiral; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/array/RemoveElement.java
leetcode/array/RemoveElement.java
//Given an array and a value, remove all instances of that value in-place and return the new length. //Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. //The order of elements can be changed. It doesn't matter what you leave beyond the new length. //Example: //Given nums = [3,2,2,3], val = 3, //Your function should return length = 2, with the first two elements of nums being 2. class RemoveElement { public int removeElement(int[] nums, int val) { int index = 0; for(int i = 0; i < nums.length; i++) { if(nums[i] != val) { nums[index++] = nums[i]; } } return index; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/array/MaximumProductSubarray.java
leetcode/array/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/leetcode/array/SpiralMatrix.java
leetcode/array/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/leetcode/array/InsertDeleteGetRandomO1.java
leetcode/array/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/array/GameOfLife.java
leetcode/array/GameOfLife.java
// According to the Wikipedia's article: "The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970." // Given a board with m by n cells, each cell has an initial state live (1) or dead (0). Each cell interacts with its eight neighbors (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article): // Any live cell with fewer than two live neighbors dies, as if caused by under-population. // Any live cell with two or three live neighbors lives on to the next generation. // Any live cell with more than three live neighbors dies, as if by over-population.. // Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction. // Write a function to compute the next state (after one update) of the board given its current state. // Follow up: // Could you solve it in-place? Remember that the board needs to be updated at the same time: You cannot update some cells first and then use their updated values to update other cells. // In this question, we represent the board using a 2D array. In principle, the board is infinite, which would cause problems when the active area encroaches the border of the array. How would you address these problems? public class GameOfLife { public void gameOfLife(int[][] board) { if(board == null || board.length == 0) { return; } int m = board.length; int n = board[0].length; for(int i = 0; i < m; i++) { for(int j = 0; j < n; j++) { int lives = liveNeighbors(board, m, n, i, j); if(board[i][j] == 1 && lives >= 2 && lives <= 3) { board[i][j] = 3; } if(board[i][j] == 0 && lives == 3) { board[i][j] = 2; } } } for(int i = 0; i < m; i++) { for(int j = 0; j < n; j++) { board[i][j] >>= 1; } } } private int liveNeighbors(int[][] board, int m, int n, int i, int j) { int lives = 0; for(int x = Math.max(i - 1, 0); x <= Math.min(i + 1, m - 1); x++) { for(int y = Math.max(j - 1, 0); y <= Math.min(j + 1, n - 1); y++) { lives += board[x][y] & 1; } } lives -= board[i][j] & 1; return lives; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/array/MissingRanges.java
leetcode/array/MissingRanges.java
// Given a sorted integer array where the range of elements are in the inclusive range [lower, upper], return its missing ranges. // For example, given [0, 1, 3, 50, 75], lower = 0 and upper = 99, return ["2", "4->49", "51->74", "76->99"]. public class MissingRanges { public List<String> findMissingRanges(int[] nums, int lower, int upper) { ArrayList<String> result = new ArrayList<String>(); for(int i = 0; i <= nums.length; i++) { long start = i == 0 ? lower : (long)nums[i - 1] + 1; long end = i == nums.length ? upper : (long)nums[i] - 1; addMissing(result, start, end); } return result; } void addMissing(ArrayList<String> result, long start, long end) { if(start > end) { return; } else if(start == end) { result.add(start + ""); } else { result.add(start + "->" + end); } } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/array/WiggleSort.java
leetcode/array/WiggleSort.java
// Given an unsorted array nums, reorder it in-place such that nums[0] <= nums[1] >= nums[2] <= nums[3].... // For example, given nums = [3, 5, 2, 1, 6, 4], one possible answer is [1, 6, 2, 5, 3, 4]. public class WiggleSort { public void wiggleSort(int[] nums) { for(int i = 1; i < nums.length; i++) { int current = nums[i - 1]; if((i % 2 == 1) == (current > nums[i])) { nums[i - 1] = nums[i]; nums[i] = current; } } } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/array/ProductofArrayExceptSelf.java
leetcode/array/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/leetcode/array/Subsets.java
leetcode/array/Subsets.java
// Given a set of distinct integers, nums, return all possible subsets. // Note: The solution set must not contain duplicate subsets. // For example, // If nums = [1,2,3], a solution is: // [ // [3], // [1], // [2], // [1,2,3], // [1,3], // [2,3], // [1,2], // [] // ] public class Subsets { public List<List<Integer>> subsets(int[] nums) { List<List<Integer>> result = new ArrayList<>(); recurse(result, nums, new Stack<>(), 0); return result; } private void recurse(List<List<Integer>> result, int[] nums, Stack path, int position) { if(position == nums.length) { result.add(new ArrayList<>(path)); return; } path.push(nums[position]); recurse(result, nums, path, position + 1); path.pop(); recurse(result, nums, path, position + 1); } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/array/FindAllNumbersDisappearedInAnArray.java
leetcode/array/FindAllNumbersDisappearedInAnArray.java
//Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once. // //Find all the elements of [1, n] inclusive that do not appear in this array. // //Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space. // //Example: // //Input: //[4,3,2,7,8,2,3,1] // //Output: //[5,6] class FindAllNumbersDisappearedInAnArray { public List<Integer> findDisappearedNumbers(int[] nums) { List<Integer> result = new ArrayList<Integer>(); HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); for(int i = 1; i <= nums.length; i++) { map.put(i, 1); } for(int i = 0; i < nums.length; i++) { if(map.containsKey(nums[i])) { map.put(nums[i], -1); } } for(int i: map.keySet()) { if(map.get(i) != -1) { result.add(i); } } return result; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/array/SubsetsII.java
leetcode/array/SubsetsII.java
// Given a collection of integers that might contain duplicates, nums, return all possible subsets. // Note: The solution set must not contain duplicate subsets. // For example, // If nums = [1,2,2], a solution is: // [ // [2], // [1], // [1,2,2], // [2,2], // [1,2], // [] // ] public class SubsetsII { public List<List<Integer>> subsetsWithDup(int[] nums) { Arrays.sort(nums); List<List<Integer>> result = new ArrayList<List<Integer>>(); if(nums.length == 0 || nums == null) { return result; } helper(nums, new ArrayList<Integer>(), 0, result); return result; } public void helper(int[] nums, ArrayList<Integer> current, int index, List<List<Integer>> result) { result.add(current); for(int i = index; i < nums.length; i++) { if(i > index && nums[i] == nums[i - 1]) { continue; } ArrayList<Integer> newCurrent = new ArrayList<Integer>(current); newCurrent.add(nums[i]); helper(nums, newCurrent, i + 1, result); } } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/array/InsertInterval.java
leetcode/array/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/leetcode/array/MajorityElement.java
leetcode/array/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/leetcode/array/LongestConsecutiveSequence.java
leetcode/array/LongestConsecutiveSequence.java
// Given an unsorted array of integers, find the length of the longest consecutive elements sequence. // For example, // Given [100, 4, 200, 1, 3, 2], // The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4. // Your algorithm should run in O(n) complexity. class LongestConsecutiveSequence { public int longestConsecutive(int[] nums) { if(nums == null || nums.length == 0) { return 0; } Set<Integer> set = new HashSet<Integer>(); for(int n: nums) { set.add(n); } int maxLength = 0; for(int n: set) { if(!set.contains(n - 1)) { int current = n; int currentMax = 1; while(set.contains(n + 1)) { currentMax++; n++; } maxLength = Math.max(maxLength, currentMax); } } return maxLength; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/array/MaximumSubarray.java
leetcode/array/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 Solution { 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/leetcode/array/MinimumPathSum.java
leetcode/array/MinimumPathSum.java
//Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right //which minimizes the sum of all numbers along its path. //Note: You can only move either down or right at any point in time. //Example 1: //[[1,3,1], //[1,5,1], //[4,2,1]] //Given the above grid map, return 7. Because the path 1→3→1→1→1 minimizes the sum. class MinimumPathSum { public int minPathSum(int[][] grid) { for(int i = 1; i < grid.length; i++) { grid[i][0] += grid[i - 1][0]; } for(int i = 1; i < grid[0].length; i++) { grid[0][i] += grid[0][i - 1]; } for(int i = 1; i < grid.length; i++) { for(int j = 1; j < grid[0].length; j++) { grid[i][j] += Math.min(grid[i - 1][j], grid[i][j - 1]); } } return grid[grid.length - 1][grid[0].length - 1]; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/array/IncreasingTripletSubsequence.java
leetcode/array/IncreasingTripletSubsequence.java
// Given an unsorted array return whether an increasing subsequence of length 3 exists or not in the array. // Formally the function should: // Return true if there exists i, j, k // such that arr[i] < arr[j] < arr[k] given 0 ≤ i < j < k ≤ n-1 else return false. // Your algorithm should run in O(n) time complexity and O(1) space complexity. // Examples: // Given [1, 2, 3, 4, 5], // return true. // Given [5, 4, 3, 2, 1], // return false. public class IncreasingTripletSequence { public boolean increasingTriplet(int[] nums) { int firstMin = Integer.MAX_VALUE; int secondMin = Integer.MAX_VALUE; for(int n : nums) { if(n <= firstMin) { firstMin = n; } else if(n < secondMin) { secondMin = n; } else if(n > secondMin) { return true; } } return false; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/array/WordSearch.java
leetcode/array/WordSearch.java
// Given a 2D board and a word, find if the word exists in the grid. // The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once. // For example, // Given board = // [ // ['A','B','C','E'], // ['S','F','C','S'], // ['A','D','E','E'] // ] // word = "ABCCED", -> returns true, // word = "SEE", -> returns true, // word = "ABCB", -> returns false. public class WordSearch { public boolean exist(char[][] board, String word) { char[] w = word.toCharArray(); for(int i = 0; i < board.length; i++) { for(int j = 0; j < board[0].length; j++) { if(search(board, i, j, w, 0)) { return true; } } } return false; } public boolean search(char[][] board, int i, int j, char[] w, int index) { if(index == w.length) { return true; } if(i < 0 || i >= board.length || j < 0 || j >= board[0].length) { return false; } if(board[i][j] != w[index]) { return false; } board[i][j] ^= 256; boolean exist = search(board, i + 1, j, w, index + 1) || search(board, i - 1, j, w, index + 1) || search(board, i, j + 1, w, index + 1) || search(board, i, j - 1, w, index + 1); board[i][j] ^= 256; return exist; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/array/SearchInRotatedSortedArray.java
leetcode/array/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/leetcode/array/SummaryRanges.java
leetcode/array/SummaryRanges.java
// Given a sorted integer array without duplicates, return the summary of its ranges. // For example, given [0,1,2,4,5,7], return ["0->2","4->5","7"]. public class SummaryRanges { public List<String> summaryRanges(int[] nums) { List<String> result = new ArrayList(); if(nums.length == 1) { result.add(nums[0] + ""); return result; } for(int i = 0; i < nums.length; i++) { int current = nums[i]; while(i + 1 < nums.length && (nums[i + 1] - nums[i] == 1)) { i++; } if(current != nums[i]) { result.add(current + "->" + nums[i]); } else { result.add(current + ""); } } return result; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/array/RotateImage.java
leetcode/array/RotateImage.java
// You are given an n x n 2D matrix representing an image. // Rotate the image by 90 degrees (clockwise). // Follow up: // Could you do this in-place? public class RotateImage { public void rotate(int[][] matrix) { for(int i = 0; i < matrix.length; i++) { for(int j = 0; j < i; j++) { int temp = matrix[i][j]; matrix[i][j] = matrix[j][i]; matrix[j][i] = temp; } } for(int i = 0; i < matrix.length; i++) { for(int j = 0; j < matrix[0].length / 2; j++) { int temp = matrix[i][j]; matrix[i][j] = matrix[i][matrix[0].length - 1 - j]; matrix[i][matrix[0].length - 1 - j] = temp; } } } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/greedy/BestTimeToBuyAndSellStockII.java
leetcode/greedy/BestTimeToBuyAndSellStockII.java
//Say you have an array for which the ith element is the price of a given stock on day i. //Design an algorithm to find the maximum profit. You may complete as many transactions as you //like (ie, buy one and sell one share of the stock multiple times). However, you may not engage //in multiple transactions at the same time (ie, you must sell the stock before you buy again). class BestTimeToBuyAndSellStockII { public int maxProfit(int[] prices) { if(prices == null || prices.length == 0) { return 0; } int profit = 0; for(int i = 0; i < prices.length - 1; i++) { if(prices[i] < prices[i + 1]) { profit += prices[i + 1] - prices[i]; } } return profit; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/dynamic-programming/LongestIncreasingSubsequence.java
leetcode/dynamic-programming/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/leetcode/dynamic-programming/EditDistance.java
leetcode/dynamic-programming/EditDistance.java
// Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.) // You have the following 3 operations permitted on a word: // a) Insert a character // b) Delete a character // c) Replace a character public class EditDistance { public int minDistance(String word1, String word2) { int m = word1.length(); int n = word2.length(); int[][] dp = new int[m + 1][n + 1]; for(int i = 0; i <= m; i++) { dp[i][0] = i; } for(int i = 0; i <= n; i++) { dp[0][i] = i; } for(int i = 0; i < m; i++) { for(int j = 0; j < n; j++) { if(word1.charAt(i) == word2.charAt(j)) { dp[i + 1][j + 1] = dp[i][j]; } else { int a = dp[i][j]; int b = dp[i][j + 1]; int c = dp[i + 1][j]; dp[i + 1][j + 1] = Math.min(a, Math.min(b, c)); dp[i + 1][j + 1]++; } } } return dp[m][n]; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/dynamic-programming/MinCostClimbingStairs.java
leetcode/dynamic-programming/MinCostClimbingStairs.java
//On a staircase, the i-th step has some non-negative cost cost[i] assigned (0 indexed). // //Once you pay the cost, you can either climb one or two steps. You need to find minimum cost to reach the top of the floor, and you can either start from the step with index 0, or the step with index 1. // //Example 1: //Input: cost = [10, 15, 20] //Output: 15 //Explanation: Cheapest is start on cost[1], pay that cost and go to the top. //Example 2: //Input: cost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1] //Output: 6 //Explanation: Cheapest is start on cost[0], and only step on 1s, skipping cost[3]. //Note: //cost will have a length in the range [2, 1000]. //Every cost[i] will be an integer in the range [0, 999]. class MinCostClimbingStairs { public int minCostClimbingStairs(int[] cost) { if(cost == null || cost.length == 0) { return 0; } if(cost.length == 1) { return cost[0]; } if(cost.length == 2) { return Math.min(cost[0], cost[1]); } int[] dp = new int[cost.length]; dp[0] = cost[0]; dp[1] = cost[1]; for(int i = 2; i < cost.length; i++) { dp[i] = Math.min(dp[i - 1] + cost[i], dp[i - 2] + cost[i]); } return Math.min(dp[cost.length - 1], dp[cost.length -2]); } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/dynamic-programming/PaintFence.java
leetcode/dynamic-programming/PaintFence.java
// There is a fence with n posts, each post can be painted with one of the k colors. // You have to paint all the posts such that no more than two adjacent fence posts have the same color. // Return the total number of ways you can paint the fence. // Note: // n and k are non-negative integers. public class PaintFence { public int numWays(int n, int k) { if(n <= 0) { return 0; } int sameColorCounts = 0; int differentColorCounts = k; for(int i = 2; i <= n; i++) { int temp = differentColorCounts; differentColorCounts = (sameColorCounts + differentColorCounts) * (k - 1); sameColorCounts = temp; } return sameColorCounts + differentColorCounts; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/dynamic-programming/PalindromicSubstrings.java
leetcode/dynamic-programming/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/leetcode/dynamic-programming/CountingBits.java
leetcode/dynamic-programming/CountingBits.java
// Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1's in their binary representation and return them as an array. // Example: // For num = 5 you should return [0,1,1,2,1,2]. // Follow up: // It is very easy to come up with a solution with run time O(n*sizeof(integer)). But can you do it in linear time O(n) /possibly in a single pass? // Space complexity should be O(n). // Can you do it like a boss? Do it without using any builtin function like __builtin_popcount in c++ or in any other language. public class CountingBits { public int[] countBits(int num) { int[] bits = new int[num + 1]; bits[0] = 0; for(int i = 1; i <= num; i++) { bits[i] = bits[i >> 1] + (i & 1); } return bits; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/dynamic-programming/UniquePaths.java
leetcode/dynamic-programming/UniquePaths.java
//A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). // //The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). // //How many possible unique paths are there? class UniquePaths { public int uniquePaths(int m, int n) { Integer[][] map = new Integer[m][n]; //only 1 way to get to ith row, 0th column (move down) for(int i = 0; i < m; i++){ map[i][0] = 1; } //only 1 way to get to ith column, 0th row (move right) for(int j= 0; j < n; j++){ map[0][j]=1; } //x ways to get to ith row, jth column (# of ways to get to //ith - 1 row, jth column + # of ways to get to jth - 1 column //ith column for(int i = 1;i < m; i++){ for(int j = 1; j < n; j++){ map[i][j] = map[i - 1][j] + map[i][j - 1]; } } return map[m - 1][n - 1]; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/dynamic-programming/SentenceScreenFitting.java
leetcode/dynamic-programming/SentenceScreenFitting.java
// Given a rows x cols screen and a sentence represented by a list of non-empty words, find how many times the given sentence can be fitted on the screen. // Note: // A word cannot be split into two lines. // The order of words in the sentence must remain unchanged. // Two consecutive words in a line must be separated by a single space. // Total words in the sentence won't exceed 100. // Length of each word is greater than 0 and won't exceed 10. // 1 ≤ rows, cols ≤ 20,000. // Example 1: // Input: // rows = 2, cols = 8, sentence = ["hello", "world"] // Output: // 1 // Explanation: // hello--- // world--- // The character '-' signifies an empty space on the screen. // Example 2: // Input: // rows = 3, cols = 6, sentence = ["a", "bcd", "e"] // Output: // 2 // Explanation: // a-bcd- // e-a--- // bcd-e- // The character '-' signifies an empty space on the screen. // Example 3: // Input: // rows = 4, cols = 5, sentence = ["I", "had", "apple", "pie"] // Output: // 1 // Explanation: // I-had // apple // pie-I // had-- // The character '-' signifies an empty space on the screen. public class SentenceScreenFitting { public int wordsTyping(String[] sentence, int rows, int cols) { String s = String.join(" ", sentence) + " "; int start = 0; int l = s.length(); for(int i = 0; i < rows; i++) { start += cols; if(s.charAt(start % l) == ' ') { start++; } else { while(start > 0 && s.charAt((start - 1) % l) != ' ') { start--; } } } return start / s.length(); } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/dynamic-programming/RegularExpressionMatching.java
leetcode/dynamic-programming/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/leetcode/dynamic-programming/CoinChange.java
leetcode/dynamic-programming/CoinChange.java
//You are given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1. //Example 1: //coins = [1, 2, 5], amount = 11 //return 3 (11 = 5 + 5 + 1) //Example 2: //coins = [2], amount = 3 //return -1. //Note: //You may assume that you have an infinite number of each kind of coin. class CoinChange { public int coinChange(int[] coins, int amount) { if(amount < 1) { return 0; } return coinChangeRecursive(coins, amount, new int[amount]); } public int coinChangeRecursive(int[] coins, int amount, int[] dp) { if(amount < 0) { return -1; } if(amount == 0) { return 0; } if(dp[amount - 1] != 0) { return dp[amount - 1]; } int min = Integer.MAX_VALUE; for(int coin: coins) { int result = coinChangeRecursive(coins, amount - coin, dp); if(result >= 0 && result < min) { min = 1 + result; } } dp[amount - 1] = min == Integer.MAX_VALUE ? -1 : min; return dp[amount - 1]; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/dynamic-programming/UniqueBinarySearchTrees.java
leetcode/dynamic-programming/UniqueBinarySearchTrees.java
// Given n, how many structurally unique BST's (binary search trees) that store values 1...n? // For example, // Given n = 3, there are a total of 5 unique BST's. // 1 3 3 2 1 // \ / / / \ \ // 3 2 1 1 3 2 // / / \ \ // 2 1 2 3 public class UniqueBinarySearchTree { public int numTrees(int n) { int[] dp = new int[n + 1]; dp[0] = 1; dp[1] = 1; for(int i = 2; i <= n; i++) { for(int j = 1; j <= i; j++) { dp[i] += dp[i - j] * dp[j - 1]; } } return dp[n]; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/dynamic-programming/BombEnemy.java
leetcode/dynamic-programming/BombEnemy.java
// Given a 2D grid, each cell is either a wall 'W', an enemy 'E' or empty '0' (the number zero), return the maximum enemies you can kill using one bomb. // The bomb kills all the enemies in the same row and column from the planted point until it hits the wall since the wall is too strong to be destroyed. // Note that you can only put the bomb at an empty cell. // Example: // For the given grid // 0 E 0 0 // E 0 W E // 0 E 0 0 // return 3. (Placing a bomb at (1,1) kills 3 enemies) public class BombEnemy { public int maxKilledEnemies(char[][] grid) { if(grid == null || grid.length == 0 || grid[0].length == 0) { return 0; } int max = 0; int row = 0; int[] col = new int[grid[0].length]; for(int i = 0; i<grid.length; i++) { for(int j = 0; j<grid[0].length;j++) { if(grid[i][j] == 'W') { continue; } if(j == 0 || grid[i][j-1] == 'W') { row = killedEnemiesRow(grid, i, j); } if(i == 0 || grid[i-1][j] == 'W') { col[j] = killedEnemiesCol(grid,i,j); } if(grid[i][j] == '0') { max = (row + col[j] > max) ? row + col[j] : max; } } } return max; } //calculate killed enemies for row i from column j private int killedEnemiesRow(char[][] grid, int i, int j) { int num = 0; while(j <= grid[0].length-1 && grid[i][j] != 'W') { if(grid[i][j] == 'E') { num++; } j++; } return num; } //calculate killed enemies for column j from row i private int killedEnemiesCol(char[][] grid, int i, int j) { int num = 0; while(i <= grid.length -1 && grid[i][j] != 'W'){ if(grid[i][j] == 'E') { num++; } i++; } return num; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/dynamic-programming/HouseRobber.java
leetcode/dynamic-programming/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 Solution { 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/leetcode/dynamic-programming/WordBreak.java
leetcode/dynamic-programming/WordBreak.java
// Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words. You may assume the dictionary does not contain duplicate words. // For example, given // s = "leetcode", // dict = ["leet", "code"]. // Return true because "leetcode" can be segmented as "leet code". public class WordBreak { public boolean wordBreak(String s, Set<String> wordDict) { boolean[] dp = new boolean[s.length() + 1]; dp[0] = true; for(int i = 1; i <= s.length(); i++) { for(int j = 0; j < i; j++) { if(dp[j] && wordDict.contains(s.substring(j, i))) { dp[i] = true; break; } } } return dp[s.length()]; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/dynamic-programming/PaintHouseII.java
leetcode/dynamic-programming/PaintHouseII.java
// There are a row of n houses, each house can be painted with one of the k colors. The cost of painting each house with a certain color is different. You have to paint all the houses such that no two adjacent houses have the same color. // The cost of painting each house with a certain color is represented by a n x k cost matrix. For example, costs[0][0] is the cost of painting house 0 with color 0; costs[1][2] is the cost of painting house 1 with color 2, and so on... Find the minimum cost to paint all houses. // Note: // All costs are positive integers. // Follow up: // Could you solve it in O(nk) runtime? public class PaintHouseII { public int minCostII(int[][] costs) { if(costs == null|| costs.length == 0) { return 0; } int m = costs.length; int n = costs[0].length; int min1 = -1; int min2 = -1; for(int i = 0; i < m; i++) { int last1 = min1; int last2 = min2; min1 = -1; min2 = -1; for(int j = 0; j < n; j++) { if(j != last1) { costs[i][j] += last1 < 0 ? 0 : costs[i - 1][last1]; } else { costs[i][j] += last2 < 0 ? 0 : costs[i - 1][last2]; } if(min1 < 0 || costs[i][j] < costs[i][min1]) { min2 = min1; min1 = j; } else if(min2 < 0 || costs[i][j] < costs[i][min2]) { min2 = j; } } } return costs[m - 1][min1]; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/dynamic-programming/CombinationSumIV.java
leetcode/dynamic-programming/CombinationSumIV.java
// Given an integer array with all positive numbers and no duplicates, find the number of possible combinations that add up to a positive integer target. // Example: // nums = [1, 2, 3] // target = 4 // The possible combination ways are: // (1, 1, 1, 1) // (1, 1, 2) // (1, 2, 1) // (1, 3) // (2, 1, 1) // (2, 2) // (3, 1) // Note that different sequences are counted as different combinations. // Therefore the output is 7. // Follow up: // What if negative numbers are allowed in the given array? // How does it change the problem? // What limitation we need to add to the question to allow negative numbers? public class CombinationSumIV { public int combinationSum4(int[] nums, int target) { int[] dp = new int[target + 1]; dp[0] = 1; for(int i = 1; i < dp.length; i++) { for(int j = 0; j < nums.length; j++) { if(i - nums[j] >= 0) { dp[i] += dp[i - nums[j]]; } } } return dp[target]; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/dynamic-programming/PaintHouse.java
leetcode/dynamic-programming/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/leetcode/dynamic-programming/MinimumPathSum.java
leetcode/dynamic-programming/MinimumPathSum.java
//Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right //which minimizes the sum of all numbers along its path. //Note: You can only move either down or right at any point in time. //Example 1: //[[1,3,1], //[1,5,1], //[4,2,1]] //Given the above grid map, return 7. Because the path 1→3→1→1→1 minimizes the sum. class MinimumPathSum { public int minPathSum(int[][] grid) { for(int i = 1; i < grid.length; i++) { grid[i][0] += grid[i - 1][0]; } for(int i = 1; i < grid[0].length; i++) { grid[0][i] += grid[0][i - 1]; } for(int i = 1; i < grid.length; i++) { for(int j = 1; j < grid[0].length; j++) { grid[i][j] += Math.min(grid[i - 1][j], grid[i][j - 1]); } } return grid[grid.length - 1][grid[0].length - 1]; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/dynamic-programming/ClimbingStairs.java
leetcode/dynamic-programming/ClimbingStairs.java
// You are climbing a stair case. It takes n steps to reach to the top. // Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? // Note: Given n will be a positive integer. public class ClimbingStairs { public int climbStairs(int n) { int[] dp = new int[n + 1]; dp[0] = 1; dp[1] = 1; for(int i = 2; i < dp.length; i++) { dp[i] = dp[i - 1] + dp[i - 2]; } return dp[dp.length - 1]; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/dynamic-programming/HouseRobberII.java
leetcode/dynamic-programming/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/leetcode/design/MinStack.java
leetcode/design/MinStack.java
//Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. //push(x) -- Push element x onto stack. //pop() -- Removes the element on top of the stack. //top() -- Get the top element. //getMin() -- Retrieve the minimum element in the stack. /** * Your MinStack object will be instantiated and called as such: * MinStack obj = new MinStack(); * obj.push(x); * obj.pop(); * int param_3 = obj.top(); * int param_4 = obj.getMin(); */ class MinStack { class Node { int data; int min; Node next; public Node(int data, int min) { this.data = data; this.min = min; this.next = null; } } Node head; /** initialize your data structure here. */ public MinStack() { } public void push(int x) { if(head == null) { head = new Node(x, x); } else { Node newNode = new Node(x, Math.min(x, head.min)); newNode.next = head; head = newNode; } } public void pop() { head = head.next; } public int top() { return head.data; } public int getMin() { return head.min; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/design/InsertDeleteGetRandomO1.java
leetcode/design/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/design/ZigZagIterator.java
leetcode/design/ZigZagIterator.java
// Given two 1d vectors, implement an iterator to return their elements alternately. // For example, given two 1d vectors: // v1 = [1, 2] // v2 = [3, 4, 5, 6] // By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1, 3, 2, 4, 5, 6]. // Follow up: What if you are given k 1d vectors? How well can your code be extended to such cases? /** * Your ZigzagIterator object will be instantiated and called as such: * ZigzagIterator i = new ZigzagIterator(v1, v2); * while (i.hasNext()) v[f()] = i.next(); */ public class ZigZagIterator { private Iterator<Integer> i; private Iterator<Integer> j; private Iterator<Integer> temp; public ZigzagIterator(List<Integer> v1, List<Integer> v2) { i = v1.iterator(); j = v2.iterator(); } public int next() { if(i.hasNext()) { temp = i; i = j; j = temp; } return j.next(); } public boolean hasNext() { return i.hasNext() || j.hasNext(); } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/hash-table/BinaryTreeVerticalOrderTraversal.java
leetcode/hash-table/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/leetcode/hash-table/IslandPerimeter.java
leetcode/hash-table/IslandPerimeter.java
// You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represents water. Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells). The island doesn't have "lakes" (water inside that isn't connected to the water around the island). One cell is a square with side length 1. The grid is rectangular, width and height don't exceed 100. Determine the perimeter of the island. // Example: // [[0,1,0,0], // [1,1,1,0], // [0,1,0,0], // [1,1,0,0]] // Answer: 16 class IslandPerimeter { public int islandPerimeter(int[][] grid) { int perimeter = 0; if(grid == null || grid.length == 0) { return perimeter; } for(int i = 0; i < grid.length; i++) { for(int j = 0; j < grid[i].length; j++) { if(grid[i][j] == 1) { perimeter += numNeighbors(grid, i, j); return perimeter; } } } return perimeter; } public int numNeighbors(int[][] grid, int x, int y) { if(x < 0 || x >= grid.length || y < 0 || y >= grid[x].length || grid[x][y] == 0) { return 1; } if(grid[x][y] == -1) { return 0; } grid[x][y] = -1; return numNeighbors(grid, x + 1, y) + numNeighbors(grid, x - 1, y) + numNeighbors(grid, x, y + 1) + numNeighbors(grid, x, y - 1); } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/hash-table/EncodeAndDecodeTinyURL.java
leetcode/hash-table/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/leetcode/hash-table/TwoSum.java
leetcode/hash-table/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/leetcode/hash-table/FirstUniqueCharacterInAString.java
leetcode/hash-table/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/leetcode/hash-table/LoggerRateLimiter.java
leetcode/hash-table/LoggerRateLimiter.java
// Design a logger system that receive stream of messages along with its timestamps, each message should be printed if and only if it is not printed in the last 10 seconds. // Given a message and a timestamp (in seconds granularity), return true if the message should be printed in the given timestamp, otherwise returns false. // It is possible that several messages arrive roughly at the same time. // Example: // Logger logger = new Logger(); // // logging string "foo" at timestamp 1 // logger.shouldPrintMessage(1, "foo"); returns true; // // logging string "bar" at timestamp 2 // logger.shouldPrintMessage(2,"bar"); returns true; // // logging string "foo" at timestamp 3 // logger.shouldPrintMessage(3,"foo"); returns false; // // logging string "bar" at timestamp 8 // logger.shouldPrintMessage(8,"bar"); returns false; // // logging string "foo" at timestamp 10 // logger.shouldPrintMessage(10,"foo"); returns false; // // logging string "foo" at timestamp 11 // logger.shouldPrintMessage(11,"foo"); returns true; public class LoggerRateLimiter { HashMap<String, Integer> messages; /** Initialize your data structure here. */ public Logger() { this.messages = new HashMap<String, Integer>(); } /** Returns true if the message should be printed in the given timestamp, otherwise returns false. If this method returns false, the message will not be printed. The timestamp is in seconds granularity. */ public boolean shouldPrintMessage(int timestamp, String message) { if(messages.containsKey(message)) { if(timestamp - messages.get(message) >= 10) { messages.put(message, timestamp); return true; } else { return false; } } else { messages.put(message, timestamp); return true; } } } /** * Your Logger object will be instantiated and called as such: * Logger obj = new Logger(); * boolean param_1 = obj.shouldPrintMessage(timestamp,message); */
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/hash-table/SingleNumberII.java
leetcode/hash-table/SingleNumberII.java
//Given an array of integers, every element appears three times except for one, //which appears exactly once. Find that single one. //Note: //Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? class SingleNumberII { public int singleNumber(int[] nums) { HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); for(int i: nums) { if(map.containsKey(i)) { map.put(i, map.get(i) + 1); } else { map.put(i, 1); } } for(int key: map.keySet()) { if(map.get(key) == 1) { return key; } } //no unique integer in nums return -1; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/hash-table/GroupShiftedStrings.java
leetcode/hash-table/GroupShiftedStrings.java
// Given a string, we can "shift" each of its letter to its successive letter, for example: "abc" -> "bcd". We can keep "shifting" which forms the sequence: // "abc" -> "bcd" -> ... -> "xyz" // Given a list of strings which contains only lowercase alphabets, group all strings that belong to the same shifting sequence. // For example, given: ["abc", "bcd", "acef", "xyz", "az", "ba", "a", "z"], // A solution is: // [ // ["abc","bcd","xyz"], // ["az","ba"], // ["acef"], // ["a","z"] // ] public class GroupShiftedStrings { public List<List<String>> groupStrings(String[] strings) { List<List<String>> result = new ArrayList<List<String>>(); HashMap<String, List<String>> map = new HashMap<String, List<String>>(); for(String s : strings) { int offset = s.charAt(0) - 'a'; String key = ""; for(int i = 0; i < s.length(); i++) { char current = (char)(s.charAt(i) - offset); if(current < 'a') { current += 26; } key += current; } if(!map.containsKey(key)) { List<String> list = new ArrayList<String>(); map.put(key, list); } map.get(key).add(s); } for(String key : map.keySet()) { List<String> list = map.get(key); Collections.sort(list); result.add(list); } return result; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/hash-table/JewelsAndStones.java
leetcode/hash-table/JewelsAndStones.java
//You're given strings J representing the types of stones that are jewels, and S representing the stones you have. //Each character in S is a type of stone you have. You want to know how many of the stones you have are also jewels. //The letters in J are guaranteed distinct, and all characters in J and S are letters. Letters are case sensitive, //so "a" is considered a different type of stone from "A". class JewelsAndStones { public int numJewelsInStones(String J, String S) { HashMap<Character, Integer> map = new HashMap<Character, Integer>(); for(char c: J.toCharArray()) { map.put(c, 1); } int numberOfJewels = 0; for(char c: S.toCharArray()) { if(map.containsKey(c)) { numberOfJewels++; } } return numberOfJewels; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/hash-table/DailyTemperatures.java
leetcode/hash-table/DailyTemperatures.java
//Given a list of daily temperatures, produce a list that, for each day in the input, tells you how many days you would have to wait until a warmer temperature. If there is no future day for which this is possible, put 0 instead. // //For example, given the list temperatures = [73, 74, 75, 71, 69, 72, 76, 73], your output should be [1, 1, 4, 2, 1, 1, 0, 0]. // //Note: The length of temperatures will be in the range [1, 30000]. Each temperature will be an integer in the range [30, 100]. class DailyTemperatures { public int[] dailyTemperatures(int[] temperatures) { int[] result = new int[temperatures.length]; Stack<Integer> stack = new Stack<Integer>(); for(int i = 0; i < temperatures.length; i++) { while(!stack.isEmpty() && temperatures[i] > temperatures[stack.peek()]) { int index = stack.pop(); result[index] = i - index; } stack.push(i); } return result; } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/hash-table/ContainsDuplicatesII.java
leetcode/hash-table/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/leetcode/hash-table/UniqueWordAbbreviation.java
leetcode/hash-table/UniqueWordAbbreviation.java
// An abbreviation of a word follows the form <first letter><number><last letter>. Below are some examples of word abbreviations: // a) it --> it (no abbreviation) // 1 // b) d|o|g --> d1g // 1 1 1 // 1---5----0----5--8 // c) i|nternationalizatio|n --> i18n // 1 // 1---5----0 // d) l|ocalizatio|n --> l10n // Assume you have a dictionary and given a word, find whether its abbreviation is unique in the dictionary. A word's abbreviation is unique if no other word from the dictionary has the same abbreviation. // Example: // Given dictionary = [ "deer", "door", "cake", "card" ] // isUnique("dear") -> // false // isUnique("cart") -> // true // isUnique("cane") -> // false // isUnique("make") -> // true import java.util.ArrayList; public class UniqueWordAbbreviation { HashMap<String, String> map; public ValidWordAbbr(String[] dictionary) { this.map = new HashMap<String, String>(); for(String word : dictionary) { String key = getKey(word); if(map.containsKey(key)) { if(!map.get(key).equals(word)) { map.put(key, ""); } } else { map.put(key, word); } } } public boolean isUnique(String word) { return !map.containsKey(getKey(word))||map.get(getKey(word)).equals(word); } public String getKey(String word) { if(word.length() <= 2) { return word; } return word.charAt(0) + Integer.toString(word.length() - 2) + word.charAt(word.length() - 1); } } // Your ValidWordAbbr object will be instantiated and called as such: // ValidWordAbbr vwa = new ValidWordAbbr(dictionary); // vwa.isUnique("Word"); // vwa.isUnique("anotherWord");
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/hash-table/MaximumSizeSubarraySumEqualsK.java
leetcode/hash-table/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