├── README.md ├── Fibonacci Modified └── solution.py ├── Power of Two └── Solution.java ├── Factorial Trailing Zeroes └── Solution.java ├── Single Number └── Solution.java ├── Climbing Stairs └── Solution.java ├── Sqrt-x └── Solution.java ├── Sum of Two Integers └── Solution.java ├── Reverse String └── Solution.java ├── Contains Duplicate └── Solution.java ├── Count Primes └── Solution.java ├── Pow-x- n └── Solution.java ├── Palindrome Permutation └── Solution.java ├── Reverse Linked List ├── solution_recursive.py ├── solution.py └── Solution.java ├── Remove Duplicates from Sorted Array II └── Solution.java ├── Minimum Moves to Equal Array Elements └── solution.py ├── Counting Bits └── Solution.java ├── Delete Node in a Linked List └── Solution.java ├── Number of 1 Bits └── Solution.java ├── Valid Perfect Square └── Solution.java ├── Maximum Product Subarray └── solution.py ├── Excel Sheet Column Title └── Solution.java ├── Power of Three └── Solution.java ├── Maximum Depth of Binary Tree └── Solution.java ├── Missing Number └── Solution.java ├── Majority Element └── Solution.java ├── Best Time to Buy and Sell Stock II └── Solution.java ├── Find Minimum in Rotated Sorted Array └── Solution.java ├── Length of Last Word └── Solution.java ├── Minimum Depth of Binary Tree └── Solution.java ├── Power of Four └── Solution.java ├── Single Element in a Sorted Array └── Solution.java ├── Remove Element └── Solution.java ├── Subarray Sum Equals K └── solution.py ├── Remove Linked List Elements └── Solution.java ├── Verify Preorder Sequence in Binary Search Tree └── Solution.java ├── Base 7 └── Solution.java ├── Array Partition I └── Solution.java ├── Find All Duplicates in an Array ├── Solution.java └── Solution_constant_space.java ├── Hamming Distance └── Solution.java ├── Jump Game └── Solution.java ├── Search Insert Position └── Solution.java ├── Reverse Bits └── Solution.java ├── Contains Duplicate II └── Solution.java ├── Integer to Roman └── Solution.java ├── Kth Largest Element in an Array └── Solution.java ├── Perfect Squares └── Solution.java ├── First Missing Positive └── Solution.java ├── Same Tree └── Solution.java ├── Lexicographical Numbers └── Solution.java ├── Maximum Product of Three Numbers └── Solution.java ├── Merge k Sorted Lists └── Solution.java ├── Number of Segments in a String └── Solution.java ├── Find the Difference └── Solution.java ├── Minimum Path Sum └── Solution.java ├── Roman to Integer └── Solution.java ├── Sum of Square Numbers └── Solution.java ├── Perfect Number └── Solution.java ├── Sum of Left Leaves └── Solution.java ├── Generate Parentheses └── Solution.java ├── Merge Intervals └── solution.py ├── Unique Binary Search Trees └── Solution.java ├── Container With Most Water └── Solution.java ├── Permutations ├── solution.py └── Solution.java ├── Valid Anagram └── Solution.java ├── First Unique Character in a String └── Solution.java ├── Intersection of Two Arrays └── Solution.java ├── Rotate Array └── Solution.java ├── Excel Sheet Column Number └── Solution.java ├── Repeated String Match └── Solution.java ├── Find All Numbers Disappeared in an Array └── Solution.java ├── Remove Duplicates from Sorted Array └── Solution.java ├── Add Digits └── Solution.java ├── Convert Sorted Array to Binary Search Tree └── Solution.java ├── Invert Binary Tree └── Solution.java ├── Meeting Rooms └── Solution.java ├── Pascal-s Triangle II └── Solution.java ├── Squares of a Sorted Array └── Solution.java ├── Balanced Binary Tree └── Solution.java ├── Binary Number with Alternating Bits └── solution.py ├── Max Consecutive Ones └── Solution.java ├── Ransom Note └── Solution.java ├── Linked List Cycle └── Solution.java ├── Maximum Length of Repeated Subarray └── Solution.java ├── Remove Duplicates from Sorted List └── Solution.java ├── Unique Paths └── Solution.java ├── Combinations └── Solution.java ├── Intersection of Two Linked Lists └── Solution.java ├── Judge Route Circle └── Solution.java ├── Longest Palindrome └── Solution.java ├── Maximum Subarray └── Solution.java ├── Move Zeroes └── Solution.java ├── Subsets └── Solution.java ├── Copy List with Random Pointer └── solution.py ├── Merge Two Sorted Lists └── Solution.java ├── Integer Break └── Solution.java ├── Integer Replacement └── Solution.java ├── Product of Array Except Self └── Solution.java ├── Flip Game └── Solution.java ├── Arranging Coins └── Solution.java ├── Moving Average from Data Stream └── Solution.java ├── Repeated DNA Sequences └── Solution.java ├── Generalized Abbreviation └── Solution.java ├── Rectangle Area └── Solution.java ├── Two Sum └── Solution.java ├── K-diff Pairs in an Array └── Solution.java ├── Minimum Time Difference └── Solution.java ├── Valid Palindrome II └── Solution.java ├── 3Sum Smaller └── Solution.java ├── Longest Consecutive Sequence └── Solution.java ├── Largest Number └── Solution.java ├── Remove Nth Node From End of List └── Solution.java ├── Daily Temperatures ├── Solution_O_n.java └── Solution_O_m+n.java ├── Insertion Sort List └── Solution.java ├── Implement strStr └── Solution.java ├── Binary Tree Inorder Traversal └── Solution.java ├── Reverse String II └── Solution.java ├── Binary Tree Preorder Traversal └── Solution.java ├── Linked List Cycle II └── Solution.java ├── Bulb Switcher └── Solution.java ├── Pascal-s Triangle └── Solution.java ├── Remove Duplicates from Sorted List II └── Solution.java ├── Shortest Word Distance └── Solution.java ├── Longest Substring Without Repeating Characters └── Solution.java ├── Find the Duplicate Number └── Solution.java ├── Longest Valid Parentheses ├── Solution.java └── solution.py ├── Find Peak Element └── Solution.java ├── Jewels and Stones └── Solution.java ├── Paint House └── Solution.java ├── Reverse Words in a String III └── Solution.java ├── Two Sum IV - Input is a BST └── Solution_recursive_O(n).java ├── Kth Smallest Element in a BST └── Solution.java ├── Longest Continuous Increasing Subsequence └── Solution.java ├── Two Sum II - Input array is sorted └── Solution.java ├── Maximum Length of Pair Chain └── Solution_nlogn.java ├── Longest Palindromic Substring └── Solution.java ├── Longest Substring with At Most Two Distinct Characters └── Solution.java ├── Path Sum └── Solution.java ├── Set Matrix Zeroes └── Solution.java ├── Valid Parentheses └── Solution.java ├── Reverse Linked List II └── Solution.java ├── Search a 2D Matrix └── Solution.java ├── Single Number III └── solution.py ├── Subsets II └── Solution.java ├── Non-decreasing Array └── Solution.java ├── Binary Tree Postorder Traversal └── Solution.java ├── House Robber └── Solution.java ├── Largest Rectangle in Histogram └── Solution.java ├── Valid Mountain Array └── Solution.java ├── Longest Substring with At Most K Distinct Characters └── Solution.java ├── Minimum Moves to Equal Array Elements II └── Solution.java ├── Convert BST to Greater Tree └── Solution.java ├── Maximum Average Subarray I └── Solution.java ├── Find Minimum in Rotated Sorted Array II └── Solution.java ├── Min Cost Climbing Stairs └── Solution.java ├── Delete Operation for Two Strings └── Solution.java ├── Subarray Product Less Than K └── Solution.java ├── Word Break └── Solution.java ├── Best Time to Buy and Sell Stock └── Solution.java ├── DI String Match └── Solution.java ├── Longest Harmonious Subsequence └── Solution.java ├── Range Sum Query - Immutable └── Solution.java ├── Sort List └── Solution.java ├── Toeplitz Matrix └── Solution.java ├── N-ary Tree Preorder Traversal └── Solution.java ├── 3-divisible Pairs └── Solution.java ├── Letter Case Permutation └── Solution.java ├── Maximal Square └── Solution.java ├── Search for a Range └── Solution.java ├── Fizz Buzz └── Solution.java ├── Convert Sorted List to Binary Search Tree └── Solution.java ├── Triangle └── Solution.java ├── Self Dividing Numbers └── Solution.java ├── First Bad Version └── Solution.java ├── Minimum Size Subarray Sum └── Solution.java ├── Number of Boomerangs └── Solution.java ├── Happy Number └── Solution.java ├── Rotate List └── Solution.java ├── Reaching Points └── Solution.java ├── Longest Palindromic Subsequence └── Solution.java ├── Minimum Absolute Difference in BST └── Solution.java ├── One Edit Distance └── Solution.java ├── Letter Combinations of a Phone Number └── Solution.java ├── Spiral Matrix II └── Solution.java ├── Trapping Rain Water └── Solution.java ├── 3Sum Closest └── Solution.java └── Majority Element II └── Solution.java /README.md: -------------------------------------------------------------------------------- 1 | # algorithms 2 | Here is the my solutions for problems in {leetcode, hackerrank, geeksforgeeks} 3 | 4 | [Source](https://github.com/dpronin/algorithms) 5 | -------------------------------------------------------------------------------- /Fibonacci Modified/solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://www.hackerrank.com/challenges/fibonacci-modified/problem 3 | 4 | This is kinda stupid problem and not related to DP but for handling big integer. That is why I used python for it. 5 | 6 | """ 7 | 8 | t1, t2, n = map(int, input().split()) 9 | for i in range(n - 1): 10 | t2, t1 = t1 + t2 * t2, t2 11 | print(t1) 12 | -------------------------------------------------------------------------------- /Power of Two/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/power-of-two 2 | // 3 | // 4 | // Given an integer, write a function to determine if it is a power of two. 5 | // 6 | // Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases. 7 | public class Solution { 8 | public boolean isPowerOfTwo(int n) { 9 | if (n <= 0) { 10 | return false; 11 | } 12 | return (n & n - 1) == 0; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Factorial Trailing Zeroes/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/factorial-trailing-zeroes 2 | // 3 | // Given an integer n, return the number of trailing zeroes in n!. 4 | // Note: Your solution should be in logarithmic time complexity. 5 | // Credits:Special thanks to @ts for adding this problem and creating all test cases. 6 | public class Solution { 7 | public int trailingZeroes(int n) { 8 | return n == 0 ? 0 : n / 5 + trailingZeroes(n / 5); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Single Number/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/single-number 2 | // 3 | // Given an array of integers, every element appears twice except for one. Find that single one. 4 | // 5 | // Note: 6 | // Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? 7 | // 8 | public class Solution { 9 | public int singleNumber(int[] nums) { 10 | int result = 0; 11 | for (int i : nums) result ^= i; 12 | return result; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Climbing Stairs/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/climbing-stairs 2 | // 3 | // You are climbing a stair case. It takes n steps to reach to the top. 4 | // Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? 5 | // 6 | // Note: Given n will be a positive integer. 7 | // 8 | public class Solution { 9 | public static int climbStairs(int n) { 10 | int a = 1, b = 1; 11 | while (n-- > 0) 12 | a = (b += a) - a; 13 | return a; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Sqrt-x/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/sqrtx 2 | // 3 | // Implement int sqrt(int x). 4 | // Compute and return the square root of x. 5 | public class Solution { 6 | public int mySqrt(int x) { 7 | if (x == 0) return 0; 8 | int l = 1, r = x; 9 | while (true) { 10 | int mid = l + (r - l) / 2; 11 | if (mid > x / mid) { 12 | r = mid - 1; 13 | } else { 14 | if (++mid > x / mid) { 15 | return --mid; 16 | } 17 | l = mid; 18 | } 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Sum of Two Integers/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/sum-of-two-integers 2 | // 3 | // Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -. 4 | // Example: 5 | // Given a = 1 and b = 2, return 3. 6 | // 7 | // Credits:Special thanks to @fujiaozhu for adding this problem and creating all test cases. 8 | public class Solution { 9 | public int getSum(int a, int b) { 10 | if (a == 0) return b; 11 | if (b == 0) return a; 12 | while (b != 0) { 13 | int i = a & b; 14 | a = a ^ b; 15 | b = i << 1; 16 | } 17 | return a; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Reverse String/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/reverse-string 2 | // 3 | // Write a function that takes a string as input and returns the string reversed. 4 | // 5 | // Example: 6 | // Given s = "hello", return "olleh". 7 | public class Solution { 8 | public String reverseString(String s) { 9 | char[] chars = s.toCharArray(); 10 | int left = 0, right = chars.length - 1; 11 | while (left < right) { 12 | char temp = chars[left]; 13 | chars[left++] = chars[right]; 14 | chars[right--] = temp; 15 | } 16 | return new String(chars); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Contains Duplicate/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/contains-duplicate 2 | // 3 | // 4 | // Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct. 5 | // 6 | public class Solution { 7 | public boolean containsDuplicate(int[] nums) { 8 | if (nums.length == 0) return false; 9 | HashSet set = new HashSet<>(); 10 | for(int i: nums) { 11 | set.add(i); 12 | } 13 | return set.size() != nums.length; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Count Primes/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/count-primes 2 | // 3 | // Description: 4 | // Count the number of prime numbers less than a non-negative number, n. 5 | // Credits:Special thanks to @mithmatt for adding this problem and creating all test cases. 6 | public class Solution { 7 | public int countPrimes(int n) { 8 | boolean[] dp = new boolean[n]; 9 | int result = 0; 10 | for (int i = 2; i < n; i++) { 11 | if (!dp[i]) result++; 12 | for (int j = 2; i * j < n; j++) { 13 | dp[i * j] = true; 14 | } 15 | } 16 | return result; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Pow-x- n/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/powx-n 2 | // 3 | // Implement pow(x, n). 4 | // 5 | // 6 | // Example 1: 7 | // 8 | // Input: 2.00000, 10 9 | // Output: 1024.00000 10 | // Example 2: 11 | // 12 | // Input: 2.10000, 3 13 | // Output: 9.26100 14 | class Solution { 15 | public double myPow(double x, int n) { 16 | if (n == 0) return 1; 17 | if (n == Integer.MIN_VALUE) return x > 1 ? 0 : 1; 18 | if (n < 0) { 19 | x = 1 / x; 20 | n = -n; 21 | } 22 | if ((n & 1) == 1) { 23 | return x * myPow(x * x, n / 2); 24 | } else { 25 | return myPow(x * x, n / 2); 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Palindrome Permutation/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/palindrome-permutation 2 | // 3 | // Given a string, determine if a permutation of the string could form a palindrome. 4 | // 5 | // For example, 6 | // "code" -> False, "aab" -> True, "carerac" -> True. 7 | class Solution { 8 | public boolean canPermutePalindrome(String s) { 9 | int[] ascii = new int[256]; 10 | for (char c : s.toCharArray()) { 11 | ascii[c]++; 12 | } 13 | boolean odds = false; 14 | for (int i : ascii) { 15 | if ((i & 1) == 1) { 16 | if (odds) return false; 17 | odds = !odds; 18 | } 19 | } 20 | return true; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Reverse Linked List/solution_recursive.py: -------------------------------------------------------------------------------- 1 | # Reverse a singly linked list. 2 | # 3 | # 4 | # Hint: 5 | # A linked list can be reversed either iteratively or recursively. Could you implement both? 6 | # 7 | # Definition for singly-linked list. 8 | # class ListNode(object): 9 | # def __init__(self, x): 10 | # self.val = x 11 | # self.next = None 12 | 13 | class Solution(object): 14 | def reverseList(self, head): 15 | """ 16 | :type head: ListNode 17 | :rtype: ListNode 18 | """ 19 | if not head or not head.next: 20 | return head 21 | temp = head.next 22 | new = self.reverseList(temp) 23 | temp.next = head 24 | head.next = None 25 | return new 26 | -------------------------------------------------------------------------------- /Remove Duplicates from Sorted Array II/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii 2 | // 3 | // Follow up for "Remove Duplicates": 4 | // What if duplicates are allowed at most twice? 5 | // 6 | // For example, 7 | // Given sorted array nums = [1,1,1,2,2,3], 8 | // 9 | // Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3. It doesn't matter what you leave beyond the new length. 10 | class Solution { 11 | public int removeDuplicates(int[] nums) { 12 | int left = 0, right = -1; 13 | while (++right < nums.length) { 14 | if (left < 2 || nums[left - 2] != nums[right]) nums[left++] = nums[right]; 15 | } 16 | return left; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Minimum Moves to Equal Array Elements/solution.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/minimum-moves-to-equal-array-elements 2 | # Given a non-empty integer array of size n, find the minimum number of moves required to make all array elements equal, where a move is incrementing n - 1 elements by 1. 3 | # 4 | # Example: 5 | # 6 | # Input: 7 | # [1,2,3] 8 | # 9 | # Output: 10 | # 3 11 | # 12 | # Explanation: 13 | # Only three moves are needed (remember each move increments two elements): 14 | # 15 | # [1,2,3] => [2,3,3] => [3,4,3] => [4,4,4] 16 | class Solution(object): 17 | def minMoves(self, nums): 18 | """ 19 | :type nums: List[int] 20 | :rtype: int 21 | """ 22 | return reduce(lambda x, y : x + y, nums) - len(nums) * min(nums) 23 | -------------------------------------------------------------------------------- /Reverse Linked List/solution.py: -------------------------------------------------------------------------------- 1 | # Reverse a singly linked list. 2 | # 3 | # 4 | # Hint: 5 | # A linked list can be reversed either iteratively or recursively. Could you implement both? 6 | # 7 | # Definition for singly-linked list. 8 | # class ListNode(object): 9 | # def __init__(self, x): 10 | # self.val = x 11 | # self.next = None 12 | 13 | class Solution(object): 14 | def reverseList(self, head): 15 | """ 16 | :type head: ListNode 17 | :rtype: ListNode 18 | """ 19 | current = head 20 | previous = None 21 | while current: 22 | temp = current.next 23 | current.next = previous 24 | previous = current 25 | current = temp 26 | return previous 27 | -------------------------------------------------------------------------------- /Counting Bits/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/counting-bits 2 | // 3 | // 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. 4 | // 5 | // 6 | // Example: 7 | public class Solution { 8 | 9 | static int humming(int i) { 10 | int result = 0; 11 | while (i != 0) { 12 | result += i & 1; 13 | i >>>= 1; 14 | } 15 | return result; 16 | } 17 | 18 | public int[] countBits(int num) { 19 | int [] result = new int[num + 1]; 20 | for (int i = 0; i <= num; i++) { 21 | result[i] = humming(i); 22 | } 23 | return result; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Delete Node in a Linked List/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/delete-node-in-a-linked-list 2 | // 3 | // 4 | // Write a function to delete a node (except the tail) in a singly linked list, given only access to that node. 5 | // 6 | // 7 | // Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node with value 3, the linked list should become 1 -> 2 -> 4 after calling your function. 8 | // 9 | /** 10 | * Definition for singly-linked list. 11 | * public class ListNode { 12 | * int val; 13 | * ListNode next; 14 | * ListNode(int x) { val = x; } 15 | * } 16 | */ 17 | public class Solution { 18 | public void deleteNode(ListNode node) { 19 | node.val = node.next.val; 20 | node.next = node.next.next; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Number of 1 Bits/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/number-of-1-bits 2 | // 3 | // Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight). 4 | // For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so the function should return 3. 5 | // Credits:Special thanks to @ts for adding this problem and creating all test cases. 6 | public class Solution { 7 | // you need to treat n as an unsigned value 8 | public int hammingWeight(int n) { 9 | int result = 0; 10 | while ( n != 0) { 11 | if ((n & 1) != 0) { 12 | result++; 13 | } 14 | n >>>= 1; 15 | } 16 | return result; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Valid Perfect Square/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/valid-perfect-square 2 | // 3 | // Given a positive integer num, write a function which returns True if num is a perfect square else False. 4 | // 5 | // Note: Do not use any built-in library function such as sqrt. 6 | // 7 | // Example 1: 8 | // 9 | // Input: 16 10 | // Returns: True 11 | // 12 | // 13 | // Example 2: 14 | // 15 | // Input: 14 16 | // Returns: False 17 | // 18 | // 19 | // Credits:Special thanks to @elmirap for adding this problem and creating all test cases. 20 | public class Solution { 21 | public boolean isPerfectSquare(int num) { 22 | long i = num; 23 | while (i * i > num) { 24 | i = (i + num / i) / 2; 25 | } 26 | return i * i == num; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Maximum Product Subarray/solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/problems/maximum-product-subarray 3 | 4 | Find the contiguous subarray within an array (containing at least one number) which has the largest product. 5 | 6 | For example, given the array [2,3,-2,4], 7 | the contiguous subarray [2,3] has the largest product = 6. 8 | """ 9 | class Solution(object): 10 | def maxProduct(self, nums): 11 | """ 12 | :type nums: List[int] 13 | :rtype: int 14 | """ 15 | minimum = maximum = result = nums.pop(0) 16 | for i in nums: 17 | temp = maximum 18 | maximum = max(maximum * i, minimum * i, i) 19 | minimum = min(temp * i, minimum * i, i) 20 | result = max(result, maximum, minimum) 21 | return result 22 | -------------------------------------------------------------------------------- /Excel Sheet Column Title/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/excel-sheet-column-title 2 | // 3 | // Given a positive integer, return its corresponding column title as appear in an Excel sheet. 4 | // For example: 5 | // 6 | // 1 -> A 7 | // 2 -> B 8 | // 3 -> C 9 | // ... 10 | // 26 -> Z 11 | // 27 -> AA 12 | // 28 -> AB 13 | // Credits:Special thanks to @ifanchu for adding this problem and creating all test cases. 14 | public class Solution { 15 | public String convertToTitle(int n) { 16 | if (n == 0) return ""; 17 | StringBuilder result = new StringBuilder(); 18 | while (n-- > 0) { 19 | result.append((char) (n % 26 + 'A')); 20 | n /= 26; 21 | } 22 | return result.reverse().toString(); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Power of Three/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/power-of-three 2 | // 3 | // 4 | // Given an integer, write a function to determine if it is a power of three. 5 | // 6 | // 7 | // Follow up: 8 | // Could you do it without using any loop / recursion? 9 | // 10 | // Credits:Special thanks to @dietpepsi for adding this problem and creating all test cases. 11 | public class Solution { 12 | public boolean isPowerOfThree(int n) { 13 | if(n==1) return true; 14 | 15 | boolean result = false; 16 | 17 | while(n>0){ 18 | int m = n%3; 19 | if(m==0){ 20 | n=n/3; 21 | if(n==1) 22 | return true; 23 | }else{ 24 | return false; 25 | } 26 | } 27 | 28 | return result; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Maximum Depth of Binary Tree/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/maximum-depth-of-binary-tree 2 | // 3 | // Given a binary tree, find its maximum depth. 4 | // The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. 5 | /** 6 | * Definition for a binary tree node. 7 | * public class TreeNode { 8 | * int val; 9 | * TreeNode left; 10 | * TreeNode right; 11 | * TreeNode(int x) { val = x; } 12 | * } 13 | */ 14 | public class Solution { 15 | public int maxDepth(TreeNode root) { 16 | if (root == null) { 17 | return 0; 18 | } 19 | int left = maxDepth(root.left); 20 | int right = maxDepth(root.right); 21 | return (left > right) ? left + 1 : right + 1; 22 | 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Missing Number/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/missing-number 2 | // 3 | // 4 | // Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array. 5 | // 6 | // For example, 7 | // Given nums = [0, 1, 3] return 2. 8 | // 9 | // 10 | // Note: 11 | // Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity? 12 | // 13 | // Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases. 14 | public class Solution { 15 | 16 | public int missingNumber(int[] nums) { 17 | int xor = nums.length; 18 | for(int i = 0; i < nums.length; i++) { 19 | xor ^= nums[i] ^ i; 20 | } 21 | return xor; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Majority Element/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/majority-element 2 | // 3 | // Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times. 4 | // You may assume that the array is non-empty and the majority element always exist in the array. 5 | // Credits:Special thanks to @ts for adding this problem and creating all test cases. 6 | public class Solution { 7 | public int majorityElement(int[] nums) { 8 | int counter = 0, result = 0; 9 | for (int i : nums) { 10 | if (counter == 0) { 11 | result = i; 12 | counter++; 13 | } 14 | else if (i == result) counter++; 15 | else counter--; 16 | } 17 | return result; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Best Time to Buy and Sell Stock II/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii 2 | // 3 | // Say you have an array for which the ith element is the price of a given stock on day i. 4 | // 5 | // 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). 6 | class Solution { 7 | public int maxProfit(int[] prices) { 8 | int result = 0; 9 | for (int i = 0; i < prices.length - 1; i++) { 10 | if (prices[i + 1] > prices[i]) { 11 | result += prices[i + 1] - prices[i]; 12 | } 13 | } 14 | return result; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Find Minimum in Rotated Sorted Array/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/find-minimum-in-rotated-sorted-array 2 | // 3 | // Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. 4 | // (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). 5 | // Find the minimum element. 6 | // You may assume no duplicate exists in the array. 7 | public class Solution { 8 | public int findMin(int[] nums) { 9 | int left = 0, right = nums.length - 1, mid = 0; 10 | while (left < right) { 11 | if (nums[left] < nums[right]) return nums[left]; 12 | mid = (left + right) / 2; 13 | if (nums[mid] >= nums[left]) 14 | left = mid + 1; 15 | else 16 | right = mid; 17 | } 18 | return nums[left]; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Length of Last Word/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/length-of-last-word 2 | // 3 | // Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string. 4 | // If the last word does not exist, return 0. 5 | // Note: A word is defined as a character sequence consists of non-space characters only. 6 | // 7 | // For example, 8 | // Given s = "Hello World", 9 | // return 5. 10 | // 11 | public class Solution { 12 | public int lengthOfLastWord(String s) { 13 | int end = s.length() - 1; 14 | while (end >= 0 && s.charAt(end) == ' ') { 15 | end--; 16 | } 17 | int start = end; 18 | while (start >= 0 && s.charAt(start) != ' ') { 19 | start--; 20 | } 21 | return end - start; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Minimum Depth of Binary Tree/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/minimum-depth-of-binary-tree 2 | // 3 | // Given a binary tree, find its minimum depth. 4 | // The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. 5 | /** 6 | * Definition for a binary tree node. 7 | * public class TreeNode { 8 | * int val; 9 | * TreeNode left; 10 | * TreeNode right; 11 | * TreeNode(int x) { val = x; } 12 | * } 13 | */ 14 | public class Solution { 15 | 16 | public int minDepth(TreeNode root) { 17 | if (root == null) return 0; 18 | int a = minDepth(root.left); 19 | int b = minDepth(root.right); 20 | if (a == 0 || b == 0) { 21 | return a + b + 1; 22 | } else { 23 | return Math.min(a, b) + 1; 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Power of Four/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/power-of-four 2 | // 3 | // 4 | // Given an integer (signed 32 bits), write a function to check whether it is a power of 4. 5 | // 6 | // Example: 7 | // Given num = 16, return true. 8 | // Given num = 5, return false. 9 | // 10 | // 11 | // Follow up: Could you solve it without loops/recursion? 12 | // 13 | // Credits:Special thanks to @yukuairoy for adding this problem and creating all test cases. 14 | public class Solution { 15 | public boolean isPowerOfFour(int num) { 16 | if (num < 0) return false; 17 | if ((num & (num - 1)) == 0) { 18 | int count = 0; 19 | while (num != 0) { 20 | count++; 21 | num >>>= 1; 22 | } 23 | return count % 2 == 1; 24 | } 25 | return false; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Single Element in a Sorted Array/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/single-element-in-a-sorted-array 2 | // 3 | // 4 | // Given a sorted array consisting of only integers where every element appears twice except for one element which appears once. Find this single element that appears only once. 5 | // 6 | // Example 1: 7 | // 8 | // Input: [1,1,2,3,3,4,4,8,8] 9 | // Output: 2 10 | // 11 | // 12 | // Example 2: 13 | // 14 | // Input: [3,3,7,7,10,11,11] 15 | // Output: 10 16 | // 17 | // 18 | // Note: 19 | // Your solution should run in O(log n) time and O(1) space. 20 | // 21 | // 22 | public class Solution { 23 | public int singleNonDuplicate(int[] nums) { 24 | for (int i = 1; i < nums.length; i += 2) { 25 | if (nums[i] != nums[i -1]) return nums[i] - 1; 26 | } 27 | return nums[nums.length - 1]; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Remove Element/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/remove-element 2 | // 3 | // Given an array and a value, remove all instances of that value in place and return the new length. 4 | // 5 | // Do not allocate extra space for another array, you must do this in place with constant memory. 6 | // The order of elements can be changed. It doesn't matter what you leave beyond the new length. 7 | // 8 | // Example: 9 | // Given input array nums = [3,2,2,3], val = 3 10 | // 11 | // Your function should return length = 2, with the first two elements of nums being 2. 12 | public class Solution { 13 | public int removeElement(int[] nums, int val) { 14 | int k = 0; 15 | for(int i = 0; i < nums.length; i++){ 16 | if(nums[i] != val){ 17 | nums[k++] = nums[i]; 18 | } 19 | } 20 | return k; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Subarray Sum Equals K/solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/problems/subarray-sum-equals-k 3 | 4 | Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k. 5 | 6 | Example 1: 7 | Input:nums = [1,1,1], k = 2 8 | Output: 2 9 | Note: 10 | The length of the array is in range [1, 20,000]. 11 | The range of numbers in the array is [-1000, 1000] and the range of the integer k is [-1e7, 1e7]. 12 | """ 13 | class Solution: 14 | def subarraySum(self, nums, k): 15 | """ 16 | :type nums: List[int] 17 | :type k: int 18 | :rtype: int 19 | """ 20 | sum = 0 21 | d = {0: 1} 22 | result = 0 23 | for i in nums: 24 | sum += i 25 | result += d.get(sum - k, 0) 26 | d[sum] = d.get(sum, 0) + 1 27 | return result 28 | -------------------------------------------------------------------------------- /Remove Linked List Elements/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/remove-linked-list-elements 2 | // 3 | // Remove all elements from a linked list of integers that have value val. 4 | // 5 | // Example 6 | // Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6 7 | // Return: 1 --> 2 --> 3 --> 4 --> 5 8 | // 9 | // Credits:Special thanks to @mithmatt for adding this problem and creating all test cases. 10 | /** 11 | * Definition for singly-linked list. 12 | * public class ListNode { 13 | * int val; 14 | * ListNode next; 15 | * ListNode(int x) { val = x; } 16 | * } 17 | */ 18 | public class Solution { 19 | public ListNode removeElements(ListNode head, int val) { 20 | if (head == null) return null; 21 | head.next = removeElements(head.next, val); 22 | return head.val == val ? head.next : head; 23 | 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Verify Preorder Sequence in Binary Search Tree/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/verify-preorder-sequence-in-binary-search-tree 2 | // 3 | // Given an array of numbers, verify whether it is the correct preorder traversal sequence of a binary search tree. 4 | // 5 | // You may assume each number in the sequence is unique. 6 | // 7 | // Follow up: 8 | // Could you do it using only constant space complexity? 9 | class Solution { 10 | public boolean verifyPreorder(int[] preorder) { 11 | int prev = Integer.MIN_VALUE; 12 | Deque deque = new LinkedList<>(); 13 | for (int i : preorder) { 14 | if (i < prev) return false; 15 | while (!deque.isEmpty() && deque.peek() <= i) { 16 | prev = deque.pop(); 17 | } 18 | deque.push(i); 19 | } 20 | return true; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Base 7/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/base-7 2 | // 3 | // Given an integer, return its base 7 string representation. 4 | // Example 1: 5 | // 6 | // Input: 100 7 | // Output: "202" 8 | // 9 | // 10 | // Example 2: 11 | // 12 | // Input: -7 13 | // Output: "-10" 14 | // 15 | // 16 | // Note: 17 | // The input will be in range of [-1e7, 1e7]. 18 | // 19 | public class Solution { 20 | public String convertToBase7(int num) { 21 | if (num == 0) return "0"; 22 | StringBuilder sb = new StringBuilder(); 23 | boolean negative = false; 24 | if (num < 0) { 25 | num *= -1; 26 | negative = true; 27 | } 28 | while (num > 0) { 29 | sb.append(num % 7); 30 | num /= 7; 31 | } 32 | if (negative) sb.append('-'); 33 | return sb.reverse().toString(); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Array Partition I/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/array-partition-i 2 | // 3 | // Given an array of 2n integers, your task is to group these integers into n pairs of integer, say (a1, b1), (a2, b2), ..., (an, bn) which makes sum of min(ai, bi) for all i from 1 to n as large as possible. 4 | // 5 | // Example 1: 6 | // Input: [1,4,3,2] 7 | // 8 | // Output: 4 9 | // Explanation: n is 2, and the maximum sum of pairs is 4 = min(1, 2) + min(3, 4). 10 | // Note: 11 | // n is a positive integer, which is in the range of [1, 10000]. 12 | // All the integers in the array will be in the range of [-10000, 10000]. 13 | class Solution { 14 | public int arrayPairSum(int[] nums) { 15 | Arrays.sort(nums); 16 | int result = 0; 17 | for (int i = 0; i < nums.length; i++) { 18 | result += nums[i++]; 19 | } 20 | return result; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Find All Duplicates in an Array/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/find-all-duplicates-in-an-array 2 | // 3 | // Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once. 4 | // Find all the elements that appear twice in this array. 5 | // Could you do it without extra space and in O(n) runtime? 6 | // 7 | // Example: 8 | // 9 | // Input: 10 | // [4,3,2,7,8,2,3,1] 11 | // 12 | // Output: 13 | // [2,3] 14 | // 15 | public class Solution { 16 | public List findDuplicates(int[] nums) { 17 | List result = new ArrayList<>(); 18 | int[] temp = new int[nums.length + 1]; 19 | for(int i: nums) { 20 | temp[i]++; 21 | } 22 | for (int i = 0; i < temp.length; i++) { 23 | if (temp[i] == 2) result.add(i); 24 | } 25 | return result; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Hamming Distance/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/hamming-distance 2 | // 3 | // The Hamming distance between two integers is the number of positions at which the corresponding bits are different. 4 | // Given two integers x and y, calculate the Hamming distance. 5 | // Note: 6 | // 0 ≤ x, y < 231. 7 | // 8 | // Example: 9 | // 10 | // Input: x = 1, y = 4 11 | // 12 | // Output: 2 13 | // 14 | // Explanation: 15 | // 1 (0 0 0 1) 16 | // 4 (0 1 0 0) 17 | // ? ? 18 | // 19 | // The above arrows point to positions where the corresponding bits are different. 20 | // 21 | // 22 | public class Solution { 23 | public int hammingDistance(int x, int y) { 24 | int result = 0; 25 | int temp = x ^ y; 26 | while (temp != 0) { 27 | result += (temp & 1); 28 | temp >>>= 1; 29 | } 30 | return result; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Jump Game/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/jump-game 2 | // 3 | // Given an array of non-negative integers, you are initially positioned at the first index of the array. 4 | // 5 | // Each element in the array represents your maximum jump length at that position. 6 | // 7 | // Determine if you are able to reach the last index. 8 | // 9 | // For example: 10 | // A = [2,3,1,1,4], return true. 11 | // 12 | // A = [3,2,1,0,4], return false. 13 | class Solution { 14 | public boolean canJump(int[] nums) { 15 | int length = nums.length; 16 | if (length < 2) return true; 17 | int sum = nums[0]; 18 | for (int i = 1; i < length - 1; i++) { 19 | if (sum == 0 && nums[i - 1] == 0) return false; 20 | if (sum-- >= length) return true; 21 | sum = Math.max(nums[i], sum); 22 | } 23 | return sum > 0; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Search Insert Position/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/search-insert-position 2 | // 3 | // Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. 4 | // You may assume no duplicates in the array. 5 | // 6 | // Here are few examples. 7 | // [1,3,5,6], 5 → 2 8 | // [1,3,5,6], 2 → 1 9 | // [1,3,5,6], 7 → 4 10 | // [1,3,5,6], 0 → 0 11 | // 12 | public class Solution { 13 | public int searchInsert(int[] nums, int target) { 14 | int left = 0; 15 | int right = nums.length - 1 ; 16 | while (left <= right) { 17 | int mid = left + (right - left) / 2; 18 | if (nums[mid] < target) { 19 | left = ++mid; 20 | } else { 21 | right = --mid; 22 | } 23 | } 24 | return left; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Reverse Bits/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/reverse-bits 2 | // 3 | // Reverse bits of a given 32 bits unsigned integer. 4 | // For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as 00111001011110000010100101000000). 5 | // 6 | // Follow up: 7 | // If this function is called many times, how would you optimize it? 8 | // 9 | // Related problem: Reverse Integer 10 | // Credits:Special thanks to @ts for adding this problem and creating all test cases. 11 | public class Solution { 12 | // you need treat n as an unsigned value 13 | public int reverseBits(int n) { 14 | int result = 0; 15 | int counter = 0; 16 | while (counter++ < 32) { 17 | result <<= 1; 18 | result |= n & 1; 19 | n >>>= 1; 20 | } 21 | return result; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Contains Duplicate II/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/contains-duplicate-ii 2 | // 3 | // 4 | // 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. 5 | // 6 | public class Solution { 7 | public boolean containsNearbyDuplicate(int[] nums, int k) { 8 | HashMap map = new HashMap<>(); 9 | for(int i = 0; i < nums.length; i++) { 10 | Integer t = map.get(nums[i]); 11 | if (t == null) { 12 | map.put(nums[i], i); 13 | } else { 14 | if (i - t <= k) { 15 | return true; 16 | } else { 17 | map.put(nums[i], i); 18 | } 19 | } 20 | } 21 | return false; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Integer to Roman/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/integer-to-roman 2 | // 3 | // Given an integer, convert it to a roman numeral. 4 | // 5 | // Input is guaranteed to be within the range from 1 to 3999. 6 | class Solution { 7 | public String intToRoman(int num) { 8 | StringBuilder sb = new StringBuilder(10); 9 | int t = 0; 10 | String[][] d = new String[][] { 11 | {"", "I", "II", "III", "VI", "V", "IV", "IIV", "IIIV", "XI", "X"}, 12 | {"", "X", "XX", "XXX", "LX", "L", "XL", "XXL", "XXXL", "CX", "C"}, 13 | {"", "C", "CC", "CCC", "DC", "D", "CD", "CCD", "CCCD", "MC", "M"}, 14 | {"", "M", "MM", "MMM"}, 15 | }; 16 | while (num > 0) { 17 | sb.append(d[t][num % 10]); 18 | num /= 10; 19 | t++; 20 | } 21 | return sb.reverse().toString(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Kth Largest Element in an Array/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/kth-largest-element-in-an-array 2 | // 3 | // 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. 4 | // 5 | // For example, 6 | // Given [3,2,1,5,6,4] and k = 2, return 5. 7 | // 8 | // Note: 9 | // You may assume k is always valid, 1 ? k ? array's length. 10 | // Credits:Special thanks to @mithmatt for adding this problem and creating all test cases. 11 | public class Solution { 12 | public int findKthLargest(int[] nums, int k) { 13 | if (nums.length == 0) return -1; 14 | if (nums.length == 1) return nums[0]; 15 | PriorityQueue queue = new PriorityQueue<>((o1, o2) -> o2 - o1); 16 | for (int i : nums) queue.add(i); 17 | while (k-- > 1) queue.poll(); 18 | return queue.poll(); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Perfect Squares/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/perfect-squares 2 | // 3 | // Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n. 4 | // 5 | // For example, given n = 12, return 3 because 12 = 4 + 4 + 4; given n = 13, return 2 because 13 = 4 + 9. 6 | // 7 | // Credits: 8 | // Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases. 9 | class Solution { 10 | public int numSquares(int n) { 11 | int[] dp = new int[n + 1]; 12 | dp[1] = 1; 13 | int localMin; 14 | for (int i = 2; i <= n; i++) { 15 | localMin = Integer.MAX_VALUE; 16 | for (int j = 1; j * j <= i; j++) { 17 | localMin = Math.min(localMin, dp[i - j * j]); 18 | } 19 | dp[i] = localMin + 1; 20 | } 21 | return dp[n]; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /First Missing Positive/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/first-missing-positive 2 | // 3 | // Given an unsorted integer array, find the first missing positive integer. 4 | // 5 | // For example, 6 | // Given [1,2,0] return 3, 7 | // and [3,4,-1,1] return 2. 8 | // 9 | // Your algorithm should run in O(n) time and uses constant space. 10 | public class Solution { 11 | public int firstMissingPositive(int[] nums) { 12 | int result = 1; 13 | for (int i = 0, length = nums.length, temp = 0; i < length; i++) { 14 | while (nums[i] < length && nums[i] > 0 && nums[i] != nums[nums[i] - 1]) { 15 | temp = nums[nums[i] - 1]; 16 | nums[nums[i] - 1] = nums[i]; 17 | nums[i] = temp; 18 | } 19 | } 20 | for (int i : nums) { 21 | if (i == result) result++; 22 | } 23 | return result; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Same Tree/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/same-tree 2 | // 3 | // 4 | // Given two binary trees, write a function to check if they are equal or not. 5 | // 6 | // Two binary trees are considered equal if they are structurally identical and the nodes have the same value. 7 | // 8 | /** 9 | * Definition for a binary tree node. 10 | * public class TreeNode { 11 | * int val; 12 | * TreeNode left; 13 | * TreeNode right; 14 | * TreeNode(int x) { val = x; } 15 | * } 16 | */ 17 | public class Solution { 18 | public boolean isSameTree(TreeNode p, TreeNode q) { 19 | if (p == null && q == null) { 20 | return true; 21 | } else if (p == null || q == null) { 22 | return false; 23 | } else { 24 | if (p.val != q.val) return false; 25 | return isSameTree(p.left, q.left) && isSameTree(p.right, q.right); 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Lexicographical Numbers/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/lexicographical-numbers 2 | // 3 | // Given an integer n, return 1 - n in lexicographical order. 4 | // 5 | // For example, given 13, return: [1,10,11,12,13,2,3,4,5,6,7,8,9]. 6 | // 7 | // Please optimize your algorithm to use less time and space. The input size may be as large as 5,000,000. 8 | public List lexicalOrder(int n) { 9 | List result = new ArrayList<>(); 10 | int ten = 10; 11 | int value = 1; 12 | int cursor = 0; 13 | while (cursor++ < n) { 14 | result.add(value); 15 | if (value * ten <= n) { 16 | value *= ten; 17 | } else { 18 | if (value >= n) { 19 | value /= ten; 20 | } 21 | value++; 22 | while (value % ten == 0) { 23 | value /= ten; 24 | } 25 | } 26 | } 27 | return result; 28 | } 29 | -------------------------------------------------------------------------------- /Maximum Product of Three Numbers/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/maximum-product-of-three-numbers 2 | // 3 | // Given an integer array, find three numbers whose product is maximum and output the maximum product. 4 | // Example 1: 5 | // 6 | // Input: [1,2,3] 7 | // Output: 6 8 | // 9 | // 10 | // Example 2: 11 | // 12 | // Input: [1,2,3,4] 13 | // Output: 24 14 | // 15 | // 16 | // Note: 17 | // 18 | // The length of the given array will be in range [3,104] and all elements are in the range [-1000, 1000]. 19 | // Multiplication of any three numbers in the input won't exceed the range of 32-bit signed integer. 20 | // 21 | // 22 | public class Solution { 23 | public int maximumProduct(int[] nums) { 24 | int length = nums.length; 25 | Arrays.sort(nums); 26 | return Math.max(nums[length - 1] * nums[length - 2] * nums[length - 3], nums[0] * nums[1] * nums[length - 1]); 27 | 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Merge k Sorted Lists/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/merge-k-sorted-lists 2 | // 3 | // 4 | // Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. 5 | // 6 | public class Solution { 7 | public ListNode mergeKLists(ListNode[] lists) { 8 | if (lists.length == 0) return null; 9 | PriorityQueue heap = new PriorityQueue<>((o1, o2) -> o1.val - o2.val); 10 | for (ListNode node : lists) { 11 | if (node != null) heap.offer(node); 12 | } 13 | ListNode dummy = new ListNode(0); 14 | ListNode cursor = dummy; 15 | while (!heap.isEmpty()) { 16 | ListNode temp = heap.poll(); 17 | cursor.next = temp; 18 | if (temp.next != null) heap.offer(temp.next); 19 | temp.next = null; 20 | cursor = cursor.next; 21 | } 22 | return dummy.next; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Number of Segments in a String/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/number-of-segments-in-a-string 2 | // 3 | // Count the number of segments in a string, where a segment is defined to be a contiguous sequence of non-space characters. 4 | // Please note that the string does not contain any non-printable characters. 5 | // Example: 6 | // 7 | // Input: "Hello, my name is John" 8 | // Output: 5 9 | // 10 | public class Solution { 11 | public int countSegments(String s) { 12 | int segments = 0; 13 | boolean flag = false; 14 | for (int i = 0; i < s.length(); i++) { 15 | if (s.charAt(i) != ' ') { 16 | flag = true; 17 | } else { 18 | if (flag) { 19 | segments++; 20 | flag = false; 21 | } 22 | } 23 | } 24 | if (flag) segments++; 25 | return segments; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Find the Difference/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/find-the-difference 2 | // 3 | // 4 | // Given two strings s and t which consist of only lowercase letters. 5 | // String t is generated by random shuffling string s and then add one more letter at a random position. 6 | // Find the letter that was added in t. 7 | // Example: 8 | // 9 | // Input: 10 | // s = "abcd" 11 | // t = "abcde" 12 | // 13 | // Output: 14 | // e 15 | // 16 | // Explanation: 17 | // 'e' is the letter that was added. 18 | // 19 | public class Solution { 20 | public char findTheDifference(String s, String t) { 21 | char[] ch1 = s.toCharArray(); 22 | char[] ch2 = t.toCharArray(); 23 | char answer = 0; 24 | for (int i = 0; i < ch2.length; i++) { 25 | answer += ch2[i]; 26 | } 27 | for (int i = 0; i < ch1.length; i++) { 28 | answer -= ch1[i]; 29 | } 30 | return answer; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Minimum Path Sum/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/minimum-path-sum 2 | // 3 | // 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. 4 | // Note: You can only move either down or right at any point in time. 5 | public class Solution { 6 | public int minPathSum(int[][] grid) { 7 | int y = grid.length; 8 | int x = grid[0].length; 9 | if (x == 0) return 0; 10 | int[] dp = new int[x]; 11 | for (int i = 0; i < y; i++) { 12 | dp[0] += grid[i][0]; 13 | for (int j = 1; j < x; j++) { 14 | if (i == 0) { 15 | dp[j] = grid[i][j] + dp[j - 1]; 16 | } else { 17 | dp[j] = Math.min(dp[j - 1] + grid[i][j], dp[j] + grid[i][j]); 18 | } 19 | } 20 | } 21 | return dp[x - 1]; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Roman to Integer/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/roman-to-integer 2 | // 3 | // Given a roman numeral, convert it to an integer. 4 | // 5 | // Input is guaranteed to be within the range from 1 to 3999. 6 | class Solution { 7 | public int romanToInt(String s) { 8 | int result = 0; 9 | for (int i = 0; i < s.length(); i++) { 10 | char c = s.charAt(i); 11 | if (c == 'M') result += 1000; 12 | if (c == 'D') result += 500; 13 | if (c == 'C') result += 100; 14 | if (c == 'L') result += 50; 15 | if (c == 'X') result += 10; 16 | if (c == 'V') result += 5; 17 | if (c == 'I') result += 1; 18 | } 19 | if (s.contains("CD") || s.contains("CM")) result -= 200; 20 | if (s.contains("XL") || s.contains("XC")) result -= 20; 21 | if (s.contains("IX") || s.contains("IV")) result -= 2; 22 | return result; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Sum of Square Numbers/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/sum-of-square-numbers 2 | // 3 | // 4 | // Given a non-negative integer c, your task is to decide whether there're two integers a and b such that a2 + b2 = c. 5 | // 6 | // Example 1: 7 | // 8 | // Input: 5 9 | // Output: True 10 | // Explanation: 1 * 1 + 2 * 2 = 5 11 | // 12 | // 13 | // Example 2: 14 | // 15 | // Input: 3 16 | // Output: False 17 | // 18 | // 19 | // 20 | public class Solution { 21 | public boolean judgeSquareSum(int c) { 22 | if (c < 3) return true; 23 | int left = 0, right = (int) Math.sqrt(c); 24 | while (left <= right) { 25 | int mid = left * left + right * right; 26 | if (mid < c) { 27 | left++; 28 | } else if (mid > c) { 29 | right--; 30 | } else { 31 | return true; 32 | } 33 | } 34 | return false; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Perfect Number/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/perfect-number/ 2 | // We define the Perfect Number is a positive integer that is equal to the sum of all its positive divisors except itself. 3 | // 4 | // Now, given an integer n, write a function that returns true when it is a perfect number and false when it is not. 5 | // Example: 6 | // Input: 28 7 | // Output: True 8 | // Explanation: 28 = 1 + 2 + 4 + 7 + 14 9 | // Note: The input number n will not exceed 100,000,000. (1e8) 10 | class Solution { 11 | public boolean checkPerfectNumber(int num) { 12 | if (num == 0 || num == 1) return false; 13 | Set set = new HashSet<>(14); 14 | int sum = 1; 15 | for (int i = 2; i < Math.sqrt(num) + 1; i++) { 16 | if (num % i == 0) { 17 | if (set.add(num / i)) sum += num / i; 18 | if (set.add(i)) sum += i; 19 | } 20 | } 21 | return sum == num; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Sum of Left Leaves/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/sum-of-left-leaves 2 | // 3 | // Find the sum of all left leaves in a given binary tree. 4 | // Example: 5 | // 6 | // 3 7 | // / \ 8 | // 9 20 9 | // / \ 10 | // 15 7 11 | // 12 | // There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24. 13 | // 14 | // 15 | /** 16 | * Definition for a binary tree node. 17 | * public class TreeNode { 18 | * int val; 19 | * TreeNode left; 20 | * TreeNode right; 21 | * TreeNode(int x) { val = x; } 22 | * } 23 | */ 24 | public class Solution { 25 | int summ = 0; 26 | 27 | public int sumOfLeftLeaves(TreeNode root) { 28 | if (root == null) return 0; 29 | if (root.left != null && root.left.left == null && root.left.right == null) summ += root.left.val; 30 | sumOfLeftLeaves(root.left); 31 | sumOfLeftLeaves(root.right); 32 | return summ; 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /Generate Parentheses/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/generate-parentheses 2 | // 3 | // 4 | // Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. 5 | // 6 | // 7 | // For example, given n = 3, a solution set is: 8 | // 9 | // 10 | // [ 11 | // "((()))", 12 | // "(()())", 13 | // "(())()", 14 | // "()(())", 15 | // "()()()" 16 | // ] 17 | // 18 | public class Solution { 19 | public List generateParenthesis(int n) { 20 | List result = new ArrayList<>(); 21 | helper(result, "", 0, 0, n); 22 | return result; 23 | } 24 | 25 | private void helper(List result, String s, int open, int close, int n) { 26 | if (s.length() == n * 2) result.add(s); 27 | else { 28 | if (open < n) helper(result, s + "(", open + 1, close, n); 29 | if (close < open) helper(result, s + ")", open, close + 1, n); 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Merge Intervals/solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/problems/merge-intervals 3 | 4 | Given a collection of intervals, merge all overlapping intervals. 5 | 6 | For example, 7 | Given [1,3],[2,6],[8,10],[15,18], 8 | return [1,6],[8,10],[15,18]. 9 | 10 | """ 11 | # Definition for an interval. 12 | # class Interval(object): 13 | # def __init__(self, s=0, e=0): 14 | # self.start = s 15 | # self.end = e 16 | 17 | class Solution(object): 18 | def merge(self, intervals): 19 | """ 20 | :type intervals: List[Interval] 21 | :rtype: List[Interval] 22 | """ 23 | result = [] 24 | i = sorted(intervals, key=lambda x: x.start) 25 | for interval in i: 26 | if result and interval.start <= result[-1].end <= interval.end: 27 | result[-1].end = interval.end 28 | elif not result or interval.start > result[-1].end: 29 | result.append(interval) 30 | return result 31 | -------------------------------------------------------------------------------- /Unique Binary Search Trees/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/unique-binary-search-trees 2 | // 3 | // Given n, how many structurally unique BST's (binary search trees) that store values 1...n? 4 | // 5 | // For example, 6 | // Given n = 3, there are a total of 5 unique BST's. 7 | // 8 | // 1 3 3 2 1 9 | // \ / / / \ \ 10 | // 3 2 1 1 3 2 11 | // / / \ \ 12 | // 2 1 2 3 13 | class Solution { 14 | public int numTrees(int n) { 15 | int[] dp = new int[n + 1]; 16 | dp[0] = 1; 17 | dp[1] = 1; 18 | for (int i = 2; i <= n; i++) { 19 | int left = 0; 20 | int right = i - 1; 21 | int temp = 0; 22 | while (right >= 0) { 23 | temp += dp[left++] * dp[right--]; 24 | } 25 | dp[i] = temp; 26 | } 27 | return dp[n]; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Container With Most Water/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/container-with-most-water 2 | // 3 | // Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water. 4 | // 5 | // Note: You may not slant the container and n is at least 2. 6 | // 7 | public class Solution { 8 | public int maxArea(int[] height) { 9 | int result = 0; 10 | int left = 0; 11 | int right = height.length - 1; 12 | while (left < right) { 13 | result = Math.max(result, Math.min(height[left], height[right]) * (right - left)); 14 | if (height[left] < height[right]) { 15 | left++; 16 | } else { 17 | right--; 18 | } 19 | } 20 | return result; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Permutations/solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/problems/permutations 3 | 4 | Given a collection of distinct numbers, return all possible permutations. 5 | 6 | For example, 7 | [1,2,3] have the following permutations: 8 | [ 9 | [1,2,3], 10 | [1,3,2], 11 | [2,1,3], 12 | [2,3,1], 13 | [3,1,2], 14 | [3,2,1] 15 | ] 16 | """ 17 | class Solution(object): 18 | def permute(self, nums): 19 | """ 20 | :type nums: List[int] 21 | :rtype: List[List[int]] 22 | """ 23 | result = [] 24 | self.helper(nums, 0, result, len(nums)) 25 | return result 26 | 27 | def helper(self, nums, current, result, max_current): 28 | if current == max_current: 29 | return result.append(nums[:]) 30 | for i in range(current, max_current): 31 | nums[i], nums[current] = nums[current], nums[i] 32 | self.helper(nums, current + 1, result, max_current) 33 | nums[i], nums[current] = nums[current], nums[i] 34 | -------------------------------------------------------------------------------- /Valid Anagram/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/valid-anagram 2 | // 3 | // Given two strings s and t, write a function to determine if t is an anagram of s. 4 | // For example, 5 | // s = "anagram", t = "nagaram", return true. 6 | // s = "rat", t = "car", return false. 7 | // 8 | // Note: 9 | // You may assume the string contains only lowercase alphabets. 10 | // Follow up: 11 | // What if the inputs contain unicode characters? How would you adapt your solution to such case? 12 | public class Solution { 13 | public boolean isAnagram(String s, String t) { 14 | if (s.length() != t.length()) return false; 15 | int a[] = new int[26]; 16 | for(int i = 0; i < s.length(); i++) { 17 | a[s.charAt(i) - 'a']++; 18 | } 19 | for(int i = 0; i < s.length(); i++) { 20 | a[t.charAt(i) - 'a']--; 21 | } 22 | for(int i: a) { 23 | if (i != 0) return false; 24 | } 25 | return true; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /First Unique Character in a String/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/first-unique-character-in-a-string 2 | // 3 | // 4 | // Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1. 5 | // 6 | // Examples: 7 | // 8 | // s = "leetcode" 9 | // return 0. 10 | // 11 | // s = "loveleetcode", 12 | // return 2. 13 | // 14 | // 15 | // 16 | // Note: You may assume the string contain only lowercase letters. 17 | // 18 | public class Solution { 19 | public int firstUniqChar(String s) { 20 | if (s.length() == 0) return -1; 21 | if (s.length() == 1) return 0; 22 | char[] letters = new char[26]; 23 | for (int i = 0; i < s.length(); i++) { 24 | letters[s.charAt(i) - 'a']++; 25 | } 26 | for (int i = 0; i < s.length(); i++) { 27 | if (letters[s.charAt(i) - 'a'] == 1) { 28 | return i; 29 | } 30 | } 31 | return -1; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Intersection of Two Arrays/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/intersection-of-two-arrays 2 | // 3 | // 4 | // Given two arrays, write a function to compute their intersection. 5 | // 6 | // Example: 7 | // Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2]. 8 | // 9 | // Note: 10 | // 11 | // Each element in the result must be unique. 12 | // The result can be in any order. 13 | // 14 | // 15 | public class Solution { 16 | public int[] intersection(int[] nums1, int[] nums2) { 17 | Set set1 = new HashSet<>(); 18 | ArrayList array = new ArrayList<>(); 19 | for (int c: nums1) { 20 | set1.add(c); 21 | } 22 | for (int c: nums2) { 23 | if (set1.contains(c) && !array.contains(c)) array.add(c); 24 | } 25 | int[] result = new int[array.size()]; 26 | for (int i = 0; i < array.size(); i++) { 27 | result[i] = array.get(i); 28 | } 29 | return result; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Rotate Array/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/rotate-array 2 | // 3 | // Rotate an array of n elements to the right by k steps. 4 | // For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4]. 5 | // Note: 6 | // Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem. 7 | // 8 | // [show hint] 9 | // Hint: 10 | // Could you do it in-place with O(1) extra space? 11 | // 12 | // Related problem: Reverse Words in a String II 13 | // Credits:Special thanks to @Freezen for adding this problem and creating all test cases. 14 | public class Solution { 15 | public void rotate(int[] nums, int k) { 16 | int[] temp = new int[nums.length]; 17 | k = k % nums.length; 18 | for (int i = 0; i < nums.length; i++) { 19 | temp[(i + k) % nums.length] = nums[i]; 20 | } 21 | for (int i = 0; i < nums.length; i++) { 22 | nums[i] = temp[i]; 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Excel Sheet Column Number/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/excel-sheet-column-number 2 | // 3 | // Related to question Excel Sheet Column Title 4 | // Given a column title as appear in an Excel sheet, return its corresponding column number. 5 | // For example: 6 | // A -> 1 7 | // B -> 2 8 | // C -> 3 9 | // ... 10 | // Z -> 26 11 | // AA -> 27 12 | // AB -> 28 13 | // Credits:Special thanks to @ts for adding this problem and creating all test cases. 14 | public class Solution { 15 | public int titleToNumber(String s) { 16 | int result = 0; 17 | double multiplicator; 18 | for (int i = 0; i < s.length(); i++) { 19 | multiplicator = Math.pow(26, s.length() - i - 1); 20 | if (multiplicator == 0) { 21 | result += s.charAt(i) - 'A' + 1 ; 22 | } else { 23 | result += (s.charAt(i) - 'A' + 1) * multiplicator ; 24 | } 25 | 26 | } 27 | return result; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Repeated String Match/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/repeated-string-match 2 | // 3 | // Given two strings A and B, find the minimum number of times A has to be repeated such that B is a substring of it. If no such solution, return -1. 4 | // 5 | // For example, with A = "abcd" and B = "cdabcdab". 6 | // 7 | // Return 3, because by repeating A three times (“abcdabcdabcd”), B is a substring of it; and B is not a substring of A repeated two times ("abcdabcd"). 8 | // 9 | // Note: 10 | // The length of A and B will be between 1 and 10000. 11 | class Solution { 12 | public int repeatedStringMatch(String A, String B) { 13 | int result = 0; 14 | StringBuilder sb = new StringBuilder(); 15 | while (sb.length() < B.length()) { 16 | sb.append(A); 17 | result++; 18 | } 19 | if (sb.toString().contains(B)) return result; 20 | sb.append(A); 21 | if (sb.toString().contains(B)) return result + 1; 22 | return -1; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Find All Numbers Disappeared in an Array/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array 2 | // 3 | // Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once. 4 | // Find all the elements of [1, n] inclusive that do not appear in this array. 5 | // Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space. 6 | // Example: 7 | // 8 | // Input: 9 | // [4,3,2,7,8,2,3,1] 10 | // 11 | // Output: 12 | // [5,6] 13 | // 14 | // 15 | public class Solution { 16 | public List findDisappearedNumbers(int[] nums) { 17 | List result = new ArrayList<>(); 18 | int temp[] = new int[nums.length]; 19 | for (int i: nums) { 20 | temp[i - 1] = 1; 21 | } 22 | for (int i = 0; i < nums.length; i++) { 23 | if (temp[i] != 1) result.add(i + 1); 24 | } 25 | return result; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Remove Duplicates from Sorted Array/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/remove-duplicates-from-sorted-array 2 | // 3 | // 4 | // Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length. 5 | // 6 | // Do not allocate extra space for another array, you must do this in place with constant memory. 7 | // 8 | // 9 | // For example, 10 | // Given input array nums = [1,1,2], 11 | // 12 | // 13 | // 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. 14 | // 15 | public class Solution { 16 | public int removeDuplicates(int[] nums) { 17 | if (nums.length < 2) return nums.length; 18 | int slow = 1; 19 | for (int fast = slow; fast < nums.length; ++fast) { 20 | if (nums[fast] != nums[fast - 1]) { 21 | nums[slow++] = nums[fast]; 22 | } 23 | } 24 | return slow; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Add Digits/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/add-digits 2 | // 3 | // 4 | // Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. 5 | // 6 | // 7 | // For example: 8 | // 9 | // 10 | // Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it. 11 | // 12 | // Follow up: 13 | // Could you do it without any loop/recursion in O(1) runtime? 14 | // 15 | // Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases. 16 | public class Solution { 17 | public int addDigits(int num) { 18 | while(num != 0) { 19 | int result = 0; 20 | int current = num; 21 | while(current != 0) { 22 | result += current % 10; 23 | current/= 10; 24 | } 25 | num = result; 26 | if (num / 10 == 0) { 27 | return result; 28 | } 29 | } 30 | return 0; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Convert Sorted Array to Binary Search Tree/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree 2 | // 3 | // Given an array where elements are sorted in ascending order, convert it to a height balanced BST. 4 | /** 5 | * Definition for a binary tree node. 6 | * public class TreeNode { 7 | * int val; 8 | * TreeNode left; 9 | * TreeNode right; 10 | * TreeNode(int x) { val = x; } 11 | * } 12 | */ 13 | public class Solution { 14 | public TreeNode sortedArrayToBST(int[] nums) { 15 | if (nums.length == 0) return null; 16 | TreeNode head = build(nums, 0, nums.length - 1); 17 | return head; 18 | } 19 | 20 | private TreeNode build(int[] nums, int left, int right) { 21 | if (left > right) return null; 22 | int mid = (right + left) / 2; 23 | TreeNode temp = new TreeNode(nums[mid]); 24 | temp.left = build(nums, left, mid - 1); 25 | temp.right = build(nums, mid + 1, right); 26 | return temp; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Invert Binary Tree/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/invert-binary-tree 2 | // 3 | // Invert a binary tree. 4 | // 4 5 | // / \ 6 | // 2 7 7 | // / \ / \ 8 | // 1 3 6 9 9 | // 10 | // to 11 | // 4 12 | // / \ 13 | // 7 2 14 | // / \ / \ 15 | // 9 6 3 1 16 | // Trivia: 17 | // This problem was inspired by this original tweet by Max Howell: 18 | // Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so fuck off. 19 | /** 20 | * Definition for a binary tree node. 21 | * public class TreeNode { 22 | * int val; 23 | * TreeNode left; 24 | * TreeNode right; 25 | * TreeNode(int x) { val = x; } 26 | * } 27 | */ 28 | public class Solution { 29 | public TreeNode invertTree(TreeNode root) { 30 | if (root == null) return null; 31 | TreeNode t = root.left; 32 | root.left = invertTree(root.right); 33 | root.right = invertTree(t); 34 | return root; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Meeting Rooms/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/meeting-rooms 2 | // 3 | // Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei), determine if a person could attend all meetings. 4 | // 5 | // For example, 6 | // Given [[0, 30],[5, 10],[15, 20]], 7 | // return false. 8 | /** 9 | * Definition for an interval. 10 | * public class Interval { 11 | * int start; 12 | * int end; 13 | * Interval() { start = 0; end = 0; } 14 | * Interval(int s, int e) { start = s; end = e; } 15 | * } 16 | */ 17 | class Solution { 18 | public boolean canAttendMeetings(Interval[] intervals) { 19 | if (intervals.length == 0) return true; 20 | Arrays.sort(intervals, Comparator.comparingInt(o -> o.start)); 21 | int end = intervals[0].end; 22 | for (int i = 1; i < intervals.length; i++) { 23 | if (intervals[i].start < end) return false; 24 | else end = intervals[i].end; 25 | } 26 | return true; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Pascal-s Triangle II/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/pascals-triangle-ii 2 | // 3 | // Given an index k, return the kth row of the Pascal's triangle. 4 | // 5 | // For example, given k = 3, 6 | // Return [1,3,3,1]. 7 | // 8 | // 9 | // Note: 10 | // Could you optimize your algorithm to use only O(k) extra space? 11 | // 12 | public class Solution { 13 | public List getRow(int rowIndex) { 14 | List result = new ArrayList<>(); 15 | if (rowIndex-- >= 0) { 16 | result.add(1); 17 | } 18 | if (rowIndex-- >= 0) { 19 | result.add(0, 1); 20 | } 21 | while (rowIndex-- >= 0) { 22 | List temp = new ArrayList<>(); 23 | for (int i = 1; i < result.size(); i++) { 24 | int t = result.get(i) + result.get(i - 1); 25 | temp.add(t); 26 | } 27 | temp.add(0, 1); 28 | temp.add(1); 29 | result = temp; 30 | } 31 | return result; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Squares of a Sorted Array/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/squares-of-a-sorted-array/solution/ 2 | // 3 | // Given an array of integers A sorted in non-decreasing order, return an array of the squares of each number, also in sorted non-decreasing order. 4 | // 5 | // Example 1: 6 | // 7 | // Input: [-4,-1,0,3,10] 8 | // Output: [0,1,9,16,100] 9 | // Example 2: 10 | // 11 | // Input: [-7,-3,2,3,11] 12 | // Output: [4,9,9,49,121] 13 | // 14 | // 15 | // Note: 16 | // 17 | // 1 <= A.length <= 10000 18 | // -10000 <= A[i] <= 10000 19 | // A is sorted in non-decreasing order. 20 | class Solution { 21 | public int[] sortedSquares(int[] A) { 22 | int[] result = new int[A.length]; 23 | int left = 0; 24 | int right = A.length - 1; 25 | for (int i = A.length - 1; i >= 0; i--) { 26 | int value = A[left]; 27 | if (Math.abs(A[left]) < Math.abs(A[right])) { 28 | value = A[right]; 29 | right--; 30 | } else { 31 | left++; 32 | } 33 | result[i] = value * value; 34 | } 35 | return result; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /Balanced Binary Tree/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/balanced-binary-tree 2 | // 3 | // Given a binary tree, determine if it is height-balanced. 4 | // 5 | // 6 | // 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. 7 | // 8 | /** 9 | * Definition for a binary tree node. 10 | * public class TreeNode { 11 | * int val; 12 | * TreeNode left; 13 | * TreeNode right; 14 | * TreeNode(int x) { val = x; } 15 | * } 16 | */ 17 | public class Solution { 18 | 19 | public boolean isBalanced(TreeNode root) { 20 | if (root == null) return true; 21 | int l = helper(root.left); 22 | int r = helper(root.right); 23 | return Math.abs(l - r) <= 1 && isBalanced(root.left) && isBalanced(root.right); 24 | } 25 | 26 | private int helper(TreeNode root) { 27 | if (root == null) return 0; 28 | return Math.max(helper(root.left), helper(root.right)) + 1; 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /Binary Number with Alternating Bits/solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/problems/binary-number-with-alternating-bits 3 | 4 | Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values. 5 | 6 | Example 1: 7 | Input: 5 8 | Output: True 9 | Explanation: 10 | The binary representation of 5 is: 101 11 | Example 2: 12 | Input: 7 13 | Output: False 14 | Explanation: 15 | The binary representation of 7 is: 111. 16 | Example 3: 17 | Input: 11 18 | Output: False 19 | Explanation: 20 | The binary representation of 11 is: 1011. 21 | Example 4: 22 | Input: 10 23 | Output: True 24 | Explanation: 25 | The binary representation of 10 is: 1010. 26 | """ 27 | class Solution: 28 | def hasAlternatingBits(self, n): 29 | """ 30 | :type n: int 31 | :rtype: bool 32 | """ 33 | prev = (n & 1 ) ^ 1 34 | while n != 0: 35 | if prev == n & 1: 36 | return False 37 | prev = n & 1 38 | n >>= 1 39 | return True 40 | -------------------------------------------------------------------------------- /Max Consecutive Ones/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/max-consecutive-ones 2 | // 3 | // Given a binary array, find the maximum number of consecutive 1s in this array. 4 | // Example 1: 5 | // 6 | // Input: [1,1,0,1,1,1] 7 | // Output: 3 8 | // Explanation: The first two digits or the last three digits are consecutive 1s. 9 | // The maximum number of consecutive 1s is 3. 10 | // 11 | // 12 | // Note: 13 | // 14 | // The input array will only contain 0 and 1. 15 | // The length of input array is a positive integer and will not exceed 10,000 16 | // 17 | // 18 | public class Solution { 19 | public int findMaxConsecutiveOnes(int[] nums) { 20 | int result = 0; 21 | int temp = 0; 22 | for(int i: nums) { 23 | if (i == 1) { 24 | temp++; 25 | } else { 26 | if (result < temp) { 27 | result = temp; 28 | } 29 | temp = 0; 30 | } 31 | } 32 | return Math.max(result, temp); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Ransom Note/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/ransom-note 2 | // 3 | // 4 | // Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom 5 | // note can be constructed from the magazines ; otherwise, it will return false. 6 | // 7 | // 8 | // Each letter in the magazine string can only be used once in your ransom note. 9 | // 10 | // Note: 11 | // You may assume that both strings contain only lowercase letters. 12 | // 13 | // 14 | // canConstruct("a", "b") -> false 15 | // canConstruct("aa", "ab") -> false 16 | // canConstruct("aa", "aab") -> true 17 | // 18 | // 19 | public class Solution { 20 | public boolean canConstruct(String ransomNote, String magazine) { 21 | int bucket[] = new int[26]; 22 | for (char c : magazine.toCharArray()) bucket[c - 'a']++; 23 | for (char c : ransomNote.toCharArray()) { 24 | if (--bucket[c - 'a'] < 0) return false; 25 | } 26 | return true; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Linked List Cycle/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/linked-list-cycle 2 | // 3 | // 4 | // Given a linked list, determine if it has a cycle in it. 5 | // 6 | // 7 | // Follow up: 8 | // Can you solve it without using extra space? 9 | // 10 | /** 11 | * Definition for singly-linked list. 12 | * class ListNode { 13 | * int val; 14 | * ListNode next; 15 | * ListNode(int x) { 16 | * val = x; 17 | * next = null; 18 | * } 19 | * } 20 | */ 21 | public class Solution { 22 | public boolean hasCycle(ListNode head) { 23 | if (head == null) return false; 24 | if (head.next == null) return false; 25 | if (head.next.next == null) return false; 26 | ListNode cursor1 = head; 27 | ListNode cursor2 = head.next.next; 28 | while(cursor2.next != null && cursor2.next.next != null) { 29 | cursor1 = cursor1.next; 30 | cursor2 = cursor2.next.next; 31 | if(cursor1 == cursor2) return true; 32 | } 33 | return false; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Maximum Length of Repeated Subarray/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/maximum-length-of-repeated-subarray 2 | // 3 | // Given two integer arrays A and B, return the maximum length of an subarray that appears in both arrays. 4 | // 5 | // Example 1: 6 | // Input: 7 | // A: [1,2,3,2,1] 8 | // B: [3,2,1,4,7] 9 | // Output: 3 10 | // Explanation: 11 | // The repeated subarray with maximum length is [3, 2, 1]. 12 | // Note: 13 | // 1 <= len(A), len(B) <= 1000 14 | // 0 <= A[i], B[i] < 100 15 | class Solution { 16 | public int findLength(int[] A, int[] B) { 17 | int y = A.length; 18 | int x = B.length; 19 | int[][] dp = new int[y + 1][x + 1]; 20 | int result = 0; 21 | for (int i = 1; i <= y; i++) { 22 | for (int j = 1; j <= x; j++) { 23 | if (A[i - 1] == B[j - 1]) { 24 | dp[i][j] = dp[i - 1][j - 1] + 1; 25 | result = Math.max(result, dp[i][j]); 26 | } 27 | } 28 | } 29 | return result; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Remove Duplicates from Sorted List/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/remove-duplicates-from-sorted-list 2 | // 3 | // 4 | // Given a sorted linked list, delete all duplicates such that each element appear only once. 5 | // 6 | // 7 | // For example, 8 | // Given 1->1->2, return 1->2. 9 | // Given 1->1->2->3->3, return 1->2->3. 10 | // 11 | /** 12 | * Definition for singly-linked list. 13 | * public class ListNode { 14 | * int val; 15 | * ListNode next; 16 | * ListNode(int x) { val = x; } 17 | * } 18 | */ 19 | public class Solution { 20 | public ListNode deleteDuplicates(ListNode head) { 21 | if(head == null || head.next == null) 22 | return head; 23 | 24 | ListNode current = head; 25 | while( current != null && current.next != null){ 26 | if(current.val == current.next.val){ 27 | current.next = current.next.next; 28 | }else{ 29 | current = current.next; 30 | } 31 | } 32 | return head; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Unique Paths/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/unique-paths 2 | // 3 | // A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). 4 | // 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). 5 | // How many possible unique paths are there? 6 | // 7 | // 8 | // Above is a 3 x 7 grid. How many possible unique paths are there? 9 | // 10 | // Note: m and n will be at most 100. 11 | public class Solution { 12 | public int uniquePaths(int m, int n) { 13 | int map[][] = new int[m][n]; 14 | for(int i = 0; i < n; i++) { 15 | map[0][i] = 1; 16 | } 17 | for(int i = 0; i < m; i++) { 18 | map[i][0] = 1; 19 | } 20 | for(int i = 1; i < m; i++) { 21 | for(int k = 1; k < n; k++) { 22 | map[i][k] = map[i - 1][k] + map[i][k - 1]; 23 | } 24 | } 25 | return map[m - 1][n - 1]; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Combinations/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/combinations 2 | // 3 | // 4 | // Given two integers n and k, return all possible combinations of k numbers out of 1 ... n. 5 | // 6 | // 7 | // For example, 8 | // If n = 4 and k = 2, a solution is: 9 | // 10 | // 11 | // [ 12 | // [2,4], 13 | // [3,4], 14 | // [2,3], 15 | // [1,2], 16 | // [1,3], 17 | // [1,4], 18 | // ] 19 | // 20 | public class Solution { 21 | public List> combine(int n, int k) { 22 | List> result = new ArrayList<>(); 23 | backtrack(n, k, 0, result, new ArrayList<>()); 24 | return result; 25 | } 26 | 27 | private void backtrack(int n, int k, int current, List> result, List temp) { 28 | if (temp.size() == k) { 29 | result.add(new ArrayList<>(temp)); 30 | } 31 | for (int i = current; i < n; i++) { 32 | temp.add(i + 1); 33 | backtrack(n, k, i + 1, result, temp); 34 | temp.remove(temp.size() - 1); 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /Intersection of Two Linked Lists/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/intersection-of-two-linked-lists 2 | // 3 | // Write a program to find the node at which the intersection of two singly linked lists begins. 4 | /** 5 | * Definition for singly-linked list. 6 | * public class ListNode { 7 | * int val; 8 | * ListNode next; 9 | * ListNode(int x) { 10 | * val = x; 11 | * next = null; 12 | * } 13 | * } 14 | */ 15 | public class Solution { 16 | public ListNode getIntersectionNode(ListNode headA, ListNode headB) { 17 | if (headA == null || headB == null) return null; 18 | ListNode h1 = headA; 19 | ListNode h2 = headB; 20 | while (h1 != h2) { 21 | if (h1 == null) { 22 | h1 = headB; 23 | } else { 24 | h1 = h1.next; 25 | } 26 | if (h2 == null) { 27 | h2 = headA; 28 | } else { 29 | h2 = h2.next; 30 | } 31 | } 32 | return h1; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Judge Route Circle/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/judge-route-circle 2 | // 3 | // 4 | // Initially, there is a Robot at position (0, 0). Given a sequence of its moves, judge if this robot makes a circle, which means it moves back to the original place. 5 | // 6 | // 7 | // The move sequence is represented by a string. And each move is represent by a character. The valid robot moves are R (Right), L (Left), U (Up) and D (down). The output should be true or false representing whether the robot makes a circle. 8 | // 9 | // Example 1: 10 | // 11 | // Input: "UD" 12 | // Output: true 13 | // 14 | // 15 | // Example 2: 16 | // 17 | // Input: "LL" 18 | // Output: false 19 | // 20 | // 21 | public class Solution { 22 | public boolean judgeCircle(String moves) { 23 | int v = 0, h = 0; 24 | for (char c : moves.toCharArray()) { 25 | if (c == 'U') v++; 26 | else if (c == 'D') v--; 27 | else if (c == 'R') h++; 28 | else if (c == 'L') h--; 29 | } 30 | return v == h && h == 0; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Longest Palindrome/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/longest-palindrome 2 | // 3 | // Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters. 4 | // This is case sensitive, for example "Aa" is not considered a palindrome here. 5 | // Note: 6 | // Assume the length of given string will not exceed 1,010. 7 | // 8 | // Example: 9 | // 10 | // Input: 11 | // "abccccdd" 12 | // 13 | // Output: 14 | // 7 15 | // 16 | // Explanation: 17 | // One longest palindrome that can be built is "dccaccd", whose length is 7. 18 | // 19 | // 20 | public class Solution { 21 | public int longestPalindrome(String s) { 22 | int a[] = new int[122-64]; 23 | for (char c: s.toCharArray()) { 24 | a[c - 'A']++; 25 | } 26 | int result = 0; 27 | int one = 0; 28 | for (int i = 0; i < a.length; i++) { 29 | if (a[i] % 2 == 1) one = 1; 30 | result += a[i] / 2; 31 | } 32 | return result * 2 + one; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Maximum Subarray/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/maximum-subarray 2 | // 3 | // 4 | // Find the contiguous subarray within an array (containing at least one number) which has the largest sum. 5 | // 6 | // 7 | // For example, given the array [-2,1,-3,4,-1,2,1,-5,4], 8 | // the contiguous subarray [4,-1,2,1] has the largest sum = 6. 9 | // 10 | // click to show more practice. 11 | // More practice: 12 | // If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle. 13 | // 14 | public class Solution { 15 | public int maxSubArray(int[] nums) { 16 | if (nums.length == 0) return 0; 17 | int result = Integer.MIN_VALUE; 18 | int helper = Integer.MIN_VALUE; 19 | int temp = 0; 20 | for (int i : nums) { 21 | helper = Math.max(helper, i); 22 | result = Math.max(result, temp); 23 | temp = temp + i < 0 ? 0 : temp + i; 24 | } 25 | return Math.max(result, temp) == 0 ? helper : Math.max(result, temp); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Move Zeroes/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/move-zeroes 2 | // 3 | // 4 | // 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. 5 | // 6 | // 7 | // For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0]. 8 | // 9 | // 10 | // Note: 11 | // 12 | // You must do this in-place without making a copy of the array. 13 | // Minimize the total number of operations. 14 | // 15 | // 16 | // Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases. 17 | public class Solution { 18 | public void moveZeroes(int[] nums) { 19 | int i = 0; 20 | for (int j = 0; j < nums.length; j++) { 21 | if (nums[i] == 0) { 22 | if (nums[j] == 0) { 23 | i--; 24 | } else { 25 | nums[i] = nums[j]; 26 | nums[j] = 0; 27 | } 28 | } 29 | i++; 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Subsets/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/subsets 2 | // 3 | // 4 | // Given a set of distinct integers, nums, return all possible subsets. 5 | // 6 | // Note: The solution set must not contain duplicate subsets. 7 | // 8 | // 9 | // For example, 10 | // If nums = [1,2,3], a solution is: 11 | // 12 | // 13 | // [ 14 | // [3], 15 | // [1], 16 | // [2], 17 | // [1,2,3], 18 | // [1,3], 19 | // [2,3], 20 | // [1,2], 21 | // [] 22 | // ] 23 | // 24 | public class Solution { 25 | public List> subsets(int[] nums) { 26 | List> result = new ArrayList<>(); 27 | backtrack(result, nums, 0, new ArrayList<>()); 28 | return result; 29 | } 30 | 31 | private void backtrack(List> result, int[] nums, int current, List temp) { 32 | result.add(new ArrayList<>(temp)); 33 | for (int i = current; i < nums.length; i++) { 34 | temp.add(nums[i]); 35 | backtrack(result, nums, i + 1, temp); 36 | temp.remove(temp.size() - 1); 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Copy List with Random Pointer/solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/problems/copy-list-with-random-pointer 3 | 4 | A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null. 5 | 6 | Return a deep copy of the list. 7 | """ 8 | # Definition for singly-linked list with a random pointer. 9 | # class RandomListNode(object): 10 | # def __init__(self, x): 11 | # self.label = x 12 | # self.next = None 13 | # self.random = None 14 | 15 | class Solution(object): 16 | def copyRandomList(self, head): 17 | """ 18 | :type head: RandomListNode 19 | :rtype: RandomListNode 20 | """ 21 | cursor = head 22 | d = {} 23 | while cursor: 24 | d[cursor] = RandomListNode(cursor.label) 25 | cursor = cursor.next 26 | cursor = head 27 | while cursor: 28 | d.get(cursor).next = d.get(cursor.next) 29 | d.get(cursor).random = d.get(cursor.random) 30 | cursor = cursor.next 31 | return d.get(head) 32 | -------------------------------------------------------------------------------- /Merge Two Sorted Lists/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/merge-two-sorted-lists 2 | // 3 | // Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists. 4 | public class Solution { 5 | public ListNode mergeTwoLists(ListNode l1, ListNode l2) { 6 | ListNode dummy = new ListNode(0); 7 | ListNode current = dummy; 8 | while (l1 != null && l2 != null) { 9 | if (l1.val < l2.val) { 10 | current.next = l1; 11 | l1 = l1.next; 12 | } else { 13 | current.next = l2; 14 | l2 = l2.next; 15 | } 16 | current = current.next; 17 | } 18 | while (l1 != null) { 19 | current.next = l1; 20 | l1 = l1.next; 21 | current = current.next; 22 | } 23 | while (l2 != null) { 24 | current.next = l2; 25 | l2 = l2.next; 26 | current = current.next; 27 | } 28 | return dummy.next; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Integer Break/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/integer-break 2 | // 3 | // Given a positive integer n, break it into the sum of at least two positive integers and maximize the product of those integers. Return the maximum product you can get. 4 | // 5 | // For example, given n = 2, return 1 (2 = 1 + 1); given n = 10, return 36 (10 = 3 + 3 + 4). 6 | // 7 | // Note: You may assume that n is not less than 2 and not larger than 58. 8 | // 9 | // Credits: 10 | // Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases. 11 | class Solution { 12 | public int integerBreak(int n) { 13 | int result = 1; 14 | if (n <= 2) return result; 15 | if (n == 3) return 2; 16 | while (n > 1) { 17 | if (n == 4) { 18 | result *= 4; 19 | n -= 4; 20 | } else if (n >= 3) { 21 | result *= 3; 22 | n -= 3; 23 | } else { 24 | result *= 2; 25 | n-= 2; 26 | } 27 | } 28 | return result; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Integer Replacement/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/integer-replacement/description/ 2 | // 3 | // Given a positive integer n and you can do operations as follow: 4 | // 5 | // If n is even, replace n with n/2. 6 | // If n is odd, you can replace n with either n + 1 or n - 1. 7 | // What is the minimum number of replacements needed for n to become 1? 8 | // 9 | // Example 1: 10 | // 11 | // Input: 12 | // 8 13 | // 14 | // Output: 15 | // 3 16 | // 17 | // Explanation: 18 | // 8 -> 4 -> 2 -> 1 19 | // Example 2: 20 | // 21 | // Input: 22 | // 7 23 | // 24 | // Output: 25 | // 4 26 | // 27 | // Explanation: 28 | // 7 -> 8 -> 4 -> 2 -> 1 29 | // or 30 | // 7 -> 6 -> 3 -> 2 -> 1 31 | class Solution { 32 | public int integerReplacement(int n) { 33 | return helper(n, 0); 34 | } 35 | 36 | private int helper(long n, int count) { 37 | if (n == 1) return count; 38 | if ((n & 1) != 1) { 39 | return helper(n >> 1, count + 1); 40 | } else { 41 | return Math.min(helper(n + 1, count + 1), helper(n - 1, count + 1)); 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /Product of Array Except Self/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/product-of-array-except-self 2 | // 3 | // 4 | // 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]. 5 | // Solve it without division and in O(n). 6 | // For example, given [1,2,3,4], return [24,12,8,6]. 7 | // 8 | // Follow up: 9 | // 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.) 10 | class Solution { 11 | public int[] productExceptSelf(int[] nums) { 12 | int length = nums.length; 13 | if (length == 0) return nums; 14 | int[] result = new int[length]; 15 | int temp = 1; 16 | for (int i = 0; i < length; i++) { 17 | result[i] = temp; 18 | temp *= nums[i]; 19 | } 20 | temp = 1; 21 | for (int i = length - 1; i >= 0; i--) { 22 | result[i] *= temp; 23 | temp *= nums[i]; 24 | } 25 | return result; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Flip Game/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/flip-game/ 2 | // 3 | // You are playing the following Flip Game with your friend: Given a string that contains only these two characters: + and -, you and your friend take turns to flip two consecutive "++" into "--". The game ends when a person can no longer make a move and therefore the other person will be the winner. 4 | // 5 | // Write a function to compute all possible states of the string after one valid move. 6 | // 7 | // For example, given s = "++++", after one move, it may become one of the following states: 8 | // 9 | // [ 10 | // "--++", 11 | // "+--+", 12 | // "++--" 13 | // ] 14 | // If there is no valid move, return an empty list []. 15 | class Solution { 16 | public List generatePossibleNextMoves(String s) { 17 | List result = new ArrayList<>(); 18 | for (int i = 1; i < s.length(); i++) { 19 | if (s.charAt(i) == '+' && s.charAt(i - 1) == '+') { 20 | result.add(s.substring(0, i - 1) + "--" + s.substring(i + 1)); 21 | } 22 | } 23 | return result; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Arranging Coins/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/arranging-coins 2 | // 3 | // You have a total of n coins that you want to form in a staircase shape, where every k-th row must have exactly k coins. 4 | // Given n, find the total number of full staircase rows that can be formed. 5 | // n is a non-negative integer and fits within the range of a 32-bit signed integer. 6 | // Example 1: 7 | // 8 | // n = 5 9 | // 10 | // The coins can form the following rows: 11 | // ¤ 12 | // ¤ ¤ 13 | // ¤ ¤ 14 | // 15 | // Because the 3rd row is incomplete, we return 2. 16 | // 17 | // 18 | // Example 2: 19 | // 20 | // n = 8 21 | // 22 | // The coins can form the following rows: 23 | // ¤ 24 | // ¤ ¤ 25 | // ¤ ¤ ¤ 26 | // ¤ ¤ 27 | // 28 | // Because the 4th row is incomplete, we return 3. 29 | // 30 | // 31 | public class Solution { 32 | public int arrangeCoins(int n) { 33 | int rows = 0; 34 | int neededCoins = 1; 35 | while (n > 0 && n >= neededCoins) { 36 | n -= neededCoins; 37 | rows++; 38 | neededCoins++; 39 | } 40 | return rows; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /Moving Average from Data Stream/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/moving-average-from-data-stream 2 | // 3 | // Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window. 4 | // 5 | // For example, 6 | // MovingAverage m = new MovingAverage(3); 7 | // m.next(1) = 1 8 | // m.next(10) = (1 + 10) / 2 9 | // m.next(3) = (1 + 10 + 3) / 3 10 | // m.next(5) = (10 + 3 + 5) / 3 11 | class MovingAverage { 12 | 13 | private Queue queue; 14 | private double sum; 15 | int size; 16 | 17 | public MovingAverage(int size) { 18 | this.queue = new LinkedList<>(); 19 | this.sum = 0; 20 | this.size = size; 21 | } 22 | 23 | public double next(int val) { 24 | if (queue.size() >= size) { 25 | sum -= queue.poll(); 26 | } 27 | sum += val; 28 | queue.offer(val); 29 | return sum / queue.size(); 30 | } 31 | } 32 | 33 | /** 34 | * Your MovingAverage object will be instantiated and called as such: 35 | * MovingAverage obj = new MovingAverage(size); 36 | * double param_1 = obj.next(val); 37 | */ 38 | -------------------------------------------------------------------------------- /Repeated DNA Sequences/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/repeated-dna-sequences 2 | // 3 | // 4 | // All DNA is composed of a series of nucleotides abbreviated as A, C, G, and T, for example: "ACGAATTCCG". When studying DNA, it is sometimes useful to identify repeated sequences within the DNA. 5 | // Write a function to find all the 10-letter-long sequences (substrings) that occur more than once in a DNA molecule. 6 | // 7 | // For example, 8 | // 9 | // Given s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT", 10 | // 11 | // Return: 12 | // ["AAAAACCCCC", "CCCCCAAAAA"]. 13 | // 14 | public class Solution { 15 | public List findRepeatedDnaSequences(String s) { 16 | HashSet set = new HashSet<>(); 17 | HashSet toResult = new HashSet<>(); 18 | int left = 0; 19 | int right = 10; 20 | while (right <= s.length()) { 21 | String t = s.substring(left, right); 22 | if (!set.add(t)) { 23 | toResult.add(t); 24 | } 25 | left++; 26 | right++; 27 | } 28 | return new ArrayList<>(toResult); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Generalized Abbreviation/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/generalized-abbreviation 2 | // 3 | // Write a function to generate the generalized abbreviations of a word. 4 | // 5 | // Example: 6 | // Given word = "word", return the following list (order does not matter): 7 | // ["word", "1ord", "w1rd", "wo1d", "wor1", "2rd", "w2d", "wo2", "1o1d", "1or1", "w1r1", "1o2", "2r1", "3d", "w3", "4"] 8 | class Solution { 9 | public List generateAbbreviations(String word) { 10 | List result = new ArrayList<>(); 11 | helper(result, word, 0, 0, ""); 12 | return result; 13 | } 14 | 15 | private void helper(List result, String word, int cursor, int length, String temp) { 16 | if (cursor == word.length()) { 17 | if (length > 0) temp += length; 18 | result.add(temp); 19 | return; 20 | } 21 | helper(result, word, cursor + 1, length + 1, temp); 22 | helper(result, word, cursor + 1, 0 , temp 23 | + (length > 0 ? length : "") 24 | + word.charAt(cursor) 25 | ); 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /Rectangle Area/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/rectangle-area 2 | // 3 | // Find the total area covered by two rectilinear rectangles in a 2D plane. 4 | // 5 | // Each rectangle is defined by its bottom left corner and top right corner as shown in the figure. 6 | // 7 | // Rectangle Area 8 | // Assume that the total area is never beyond the maximum possible value of int. 9 | // 10 | // Credits: 11 | // Special thanks to @mithmatt for adding this problem, creating the above image and all test cases. 12 | class Solution { 13 | public int computeArea(int A, int B, int C, int D, 14 | int E, int F, int G, int H) { 15 | int firstArea = (C - A) * (D - B); 16 | int secondArea = (G - E) * (H - F); 17 | int overlappedArea = 0; 18 | int left = Math.max(A, E); 19 | int bottom = Math.max(B, F); 20 | int right = Math.min(C, G); 21 | int top = Math.min(D, H); 22 | if (right > left && top > bottom) { 23 | overlappedArea = (right - left) * (top - bottom); 24 | } 25 | 26 | return firstArea + secondArea - overlappedArea; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Two Sum/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/two-sum 2 | // 3 | // Given an array of integers, return indices of the two numbers such that they add up to a specific target. 4 | // You may assume that each input would have exactly one solution, and you may not use the same element twice. 5 | // 6 | // Example: 7 | // 8 | // Given nums = [2, 7, 11, 15], target = 9, 9 | // 10 | // Because nums[0] + nums[1] = 2 + 7 = 9, 11 | // return [0, 1]. 12 | // 13 | // 14 | public class Solution { 15 | 16 | public int[] twoSum(int[] nums, int target) { 17 | int length = nums.length; 18 | int first = -1; 19 | int second = -1; 20 | if (length == 0) return new int[]{first, second}; 21 | Map map = new HashMap<>(); 22 | for (int i = 0; i < length; i++) { 23 | if (map.containsKey(target - nums[i])) { 24 | first = map.get(target - nums[i]); 25 | second = i; 26 | break; 27 | } else { 28 | map.put(nums[i], i); 29 | } 30 | } 31 | return new int[]{first, second}; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /K-diff Pairs in an Array/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/k-diff-pairs-in-an-array 2 | // 3 | // 4 | // Given an array of integers and an integer k, you need to find the number of unique k-diff pairs in the array. Here a k-diff pair is defined as an integer pair (i, j), where i and j are both numbers in the array and their absolute difference is k. 5 | // 6 | // Example 1: 7 | // 8 | // Input: [3, 1, 4, 1, 5], k = 2 9 | // Output: 2 10 | // Explanation: There are two 2-diff pairs in the array, (1, 3) and (3, 5). 11 | public class Solution { 12 | public int findPairs(int[] nums, int k) { 13 | if (k < 0) return 0; 14 | int result = 0; 15 | Map map = new HashMap<>(); 16 | for (int i : nums) { 17 | map.put(i, map.getOrDefault(i, 0) + 1); 18 | } 19 | for (Map.Entry entry : map.entrySet()) { 20 | if (k == 0) { 21 | if (entry.getValue() >= 2) result++; 22 | } else { 23 | if (map.containsKey(entry.getKey() + k)) result++; 24 | } 25 | } 26 | return result; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Minimum Time Difference/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/minimum-time-difference/ 2 | // 3 | // Given a list of 24-hour clock time points in "Hour:Minutes" format, find the minimum minutes difference between any two time points in the list. 4 | // Example 1: 5 | // Input: ["23:59","00:00"] 6 | // Output: 1 7 | // Note: 8 | // The number of time points in the given list is at least 2 and won't exceed 20000. 9 | // The input time is legal and ranges from 00:00 to 23:59. 10 | class Solution { 11 | public int findMinDifference(List timePoints) { 12 | List times = new ArrayList<>(); 13 | for (String time : timePoints) { 14 | times.add(toInt(time)); 15 | } 16 | Collections.sort(times); 17 | int result = Integer.MAX_VALUE; 18 | for (int i = 1; i < times.size(); i++) { 19 | result = Math.min(times.get(i) - times.get(i - 1), result); 20 | } 21 | return Math.min(result, times.get(0) + (1440 - times.get(times.size() - 1))); 22 | } 23 | 24 | private int toInt(String time) { 25 | return ((time.charAt(0) - '0')* 10 + (time.charAt(1) - '0')) * 60 + (time.charAt(3) - '0') * 10 + (time.charAt(4) - '0'); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Valid Palindrome II/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/valid-palindrome-ii/ 2 | // 3 | // Given a non-empty string s, you may delete at most one character. Judge whether you can make it a palindrome. 4 | // 5 | // Example 1: 6 | // Input: "aba" 7 | // Output: True 8 | // Example 2: 9 | // Input: "abca" 10 | // Output: True 11 | // Explanation: You could delete the character 'c'. 12 | // Note: 13 | // The string will only contain lowercase characters a-z. The maximum length of the string is 50000. 14 | class Solution { 15 | public boolean validPalindrome(String s) { 16 | char[] array = s.toCharArray(); 17 | for (int left = 0, right = array.length - 1; left < right; left++, right--) { 18 | if (array[left] != array[right]) { 19 | return helper(array, left + 1, right) || helper(array, left, right - 1); 20 | } 21 | } 22 | return true; 23 | } 24 | 25 | private boolean helper(char[] array, int left, int right) { 26 | while (left < right) { 27 | if (array[left++] != array[right--]) return false; 28 | } 29 | return true; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /3Sum Smaller/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/3sum-smaller 2 | // 3 | // 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. 4 | // 5 | // For example, given nums = [-2, 0, 1, 3], and target = 2. 6 | // 7 | // Return 2. Because there are two triplets which sums are less than 2: 8 | // 9 | // [-2, 0, 1] 10 | // [-2, 0, 3] 11 | // Follow up: 12 | // Could you solve it in O(n2) runtime? 13 | class Solution { 14 | public int threeSumSmaller(int[] nums, int target) { 15 | int result = 0; 16 | Arrays.sort(nums); 17 | int length = nums.length; 18 | for (int i = 0; i < length - 2; i++) { 19 | int left = i + 1; 20 | int right = length - 1; 21 | while (left < right) { 22 | while (nums[i] + nums[left] + nums[right] < target && left < right) { 23 | result += right - left; 24 | left++; 25 | } 26 | right--; 27 | } 28 | } 29 | return result; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Longest Consecutive Sequence/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/longest-consecutive-sequence 2 | // 3 | // 4 | // Given an unsorted array of integers, find the length of the longest consecutive elements sequence. 5 | // 6 | // 7 | // For example, 8 | // Given [100, 4, 200, 1, 3, 2], 9 | // The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4. 10 | // 11 | // 12 | // Your algorithm should run in O(n) complexity. 13 | // 14 | class Solution { 15 | public int longestConsecutive(int[] nums) { 16 | if (nums.length == 0) return 0; 17 | int result = 1; 18 | Map map = new HashMap<>(); 19 | for (int i : nums) { 20 | if (map.containsKey(i)) continue; 21 | int l = map.getOrDefault(i - 1, 0); 22 | int r = map.getOrDefault(i + 1, 0); 23 | int temp = l + r + 1; // at least 1 consecutive digit is current digit itself 24 | map.put(i, temp); 25 | map.put(i - l, temp); 26 | map.put(i + r, temp); 27 | result = Math.max(result, temp); 28 | } 29 | return result; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Largest Number/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/largest-number 2 | // 3 | // Given a list of non negative integers, arrange them such that they form the largest number. 4 | // For example, given [3, 30, 34, 5, 9], the largest formed number is 9534330. 5 | // Note: The result may be very large, so you need to return a string instead of an integer. 6 | // Credits:Special thanks to @ts for adding this problem and creating all test cases. 7 | public class Solution { 8 | public String largestNumber(int[] nums) { 9 | StringBuilder sb = new StringBuilder(nums.length); 10 | PriorityQueue queue = new PriorityQueue<>((o1, o2) -> { 11 | String a = o1 + o2; 12 | String b = o2 + o1; 13 | return a.compareTo(b); 14 | }); 15 | for (int i : nums) { 16 | queue.offer(String.valueOf(i)); 17 | } 18 | while (!queue.isEmpty()) { 19 | sb.insert(0, queue.poll()); 20 | } 21 | int i = 0; 22 | while (sb.charAt(0) == '0' && sb.length() > 1) { 23 | sb.deleteCharAt(i); 24 | } 25 | return sb.toString(); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Remove Nth Node From End of List/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/remove-nth-node-from-end-of-list 2 | // 3 | // Given a linked list, remove the nth node from the end of list and return its head. 4 | // 5 | // For example, 6 | // 7 | // Given linked list: 1->2->3->4->5, and n = 2. 8 | // 9 | // After removing the second node from the end, the linked list becomes 1->2->3->5. 10 | // 11 | // 12 | // Note: 13 | // Given n will always be valid. 14 | // Try to do this in one pass. 15 | // 16 | public class Solution { 17 | public ListNode removeNthFromEnd(ListNode head, int n) { 18 | if (head == null) return null; 19 | if (head.next == null && n == 1) return null; 20 | ListNode slow = head; 21 | ListNode fast = head; 22 | int counter = 0; 23 | while (counter < n) { 24 | fast = fast.next; 25 | counter++; 26 | } 27 | if (fast == null) return head.next; 28 | while (fast.next != null) { 29 | fast = fast.next; 30 | slow = slow.next; 31 | } 32 | slow.next = slow.next.next; 33 | return head; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Daily Temperatures/Solution_O_n.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/daily-temperatures 2 | // 3 | // 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. 4 | // 5 | // 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]. 6 | // 7 | // Note: The length of temperatures will be in the range [1, 30000]. Each temperature will be an integer in the range [30, 100]. 8 | class Solution { 9 | public int[] dailyTemperatures(int[] temperatures) { 10 | int length = temperatures.length; 11 | int[] result = new int[length]; 12 | Deque deque = new LinkedList<>(); 13 | for (int i = length - 1; i >= 0; i--) { 14 | while (!deque.isEmpty() && temperatures[deque.peek()] <= temperatures[i]) { 15 | deque.pop(); 16 | } 17 | result[i] = deque.isEmpty() ? 0 : deque.peek() - i; 18 | deque.push(i); 19 | } 20 | return result; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Insertion Sort List/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/insertion-sort-list 2 | // 3 | // Sort a linked list using insertion sort. 4 | /** 5 | * Definition for singly-linked list. 6 | * public class ListNode { 7 | * int val; 8 | * ListNode next; 9 | * ListNode(int x) { val = x; } 10 | * } 11 | */ 12 | public class Solution { 13 | public ListNode insertionSortList(ListNode head) { 14 | if (head == null) return null; 15 | ListNode dummy = new ListNode(0); 16 | dummy.next = head; 17 | ListNode current = head; 18 | while (current.next != null) { 19 | if (current.val < current.next.val) { 20 | current = current.next; 21 | } else { 22 | ListNode temp = current.next; 23 | ListNode toInsert = dummy; 24 | while (toInsert.next.val < temp.val) { 25 | toInsert = toInsert.next; 26 | } 27 | current.next = temp.next; 28 | temp.next = toInsert.next; 29 | toInsert.next = temp; 30 | } 31 | } 32 | return dummy.next; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Find All Duplicates in an Array/Solution_constant_space.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/find-all-duplicates-in-an-array 2 | // 3 | // Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once. 4 | // Find all the elements that appear twice in this array. 5 | // Could you do it without extra space and in O(n) runtime? 6 | // 7 | // Example: 8 | // 9 | // Input: 10 | // [4,3,2,7,8,2,3,1] 11 | // 12 | // Output: 13 | // [2,3] 14 | // 15 | class Solution { 16 | public List findDuplicates(int[] nums) { 17 | List result = new ArrayList<>(); 18 | for (int i = 0; i < nums.length; i++) { 19 | if (nums[i] > 0) { 20 | int next = nums[i]; 21 | nums[i] = -nums[i]; 22 | while (next > 0) { 23 | if (nums[next - 1] == 0) { 24 | result.add(next); 25 | } 26 | int temp = nums[next - 1]; 27 | nums[next - 1] = 0; 28 | next = temp; 29 | } 30 | } 31 | } 32 | return result; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Implement strStr/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/implement-strstr 2 | // 3 | // 4 | // Implement strStr(). 5 | // 6 | // 7 | // Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. 8 | // 9 | public class Solution { 10 | 11 | private static boolean checkStrings(char[] a, char[] b, int i, int bl) { 12 | for (int start = 0, end = bl - 1; start <= end; start++, end--) { 13 | if (a[i + start] != b[start] || a[i + bl - start - 1] != b[end]) return false; 14 | } 15 | return true; 16 | } 17 | 18 | public int strStr(String haystack, String needle) { 19 | if (haystack.isEmpty() && needle.isEmpty()) return 0; 20 | if (needle.isEmpty()) return 0; 21 | char[] a = haystack.toCharArray(); 22 | char[] b = needle.toCharArray(); 23 | int al = a.length; 24 | int bl = b.length; 25 | if (al == bl && haystack.equals(needle)) return 0; 26 | for (int i = 0; i < al - bl + 1; i++) { 27 | if (checkStrings(a, b, i, bl)) { 28 | return i; 29 | } 30 | } 31 | return -1; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Binary Tree Inorder Traversal/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/binary-tree-inorder-traversal 2 | // 3 | // Given a binary tree, return the inorder traversal of its nodes' values. 4 | // 5 | // For example: 6 | // Given binary tree [1,null,2,3], 7 | // 8 | // 1 9 | // \ 10 | // 2 11 | // / 12 | // 3 13 | // 14 | // 15 | // 16 | // return [1,3,2]. 17 | // 18 | // Note: Recursive solution is trivial, could you do it iteratively? 19 | /** 20 | * Definition for a binary tree node. 21 | * public class TreeNode { 22 | * int val; 23 | * TreeNode left; 24 | * TreeNode right; 25 | * TreeNode(int x) { val = x; } 26 | * } 27 | */ 28 | public class Solution { 29 | public List inorderTraversal(TreeNode root) { 30 | List result = new ArrayList<>(); 31 | if (root == null) return result; 32 | recursion(root, result); 33 | return result; 34 | } 35 | 36 | private void recursion(TreeNode root, List result) { 37 | if (root == null) return; 38 | recursion(root.left, result); 39 | result.add(root.val); 40 | recursion(root.right, result); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /Reverse String II/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/reverse-string-ii/description/ 2 | // 3 | // Given a string and an integer k, you need to reverse the first k characters for every 2k characters counting from the start of the string. If there are less than k characters left, reverse all of them. If there are less than 2k but greater than or equal to k characters, then reverse the first k characters and left the other as original. 4 | // Example: 5 | // Input: s = "abcdefg", k = 2 6 | // Output: "bacdfeg" 7 | // Restrictions: 8 | // The string consists of lower English letters only. 9 | // Length of the given string and k will in the range [1, 10000] 10 | class Solution { 11 | public String reverseStr(String s, int k) { 12 | char[] c = s.toCharArray(); 13 | for (int i = 0; i < c.length; i += k * 2) { 14 | reverse(c, i, Math.min(i + k - 1, c.length - 1)); 15 | } 16 | return new String(c); 17 | } 18 | 19 | private void reverse(char[] c, int left, int right) { 20 | while (left < right) { 21 | char t = c[left]; 22 | c[left++] = c[right]; 23 | c[right--] = t; 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Binary Tree Preorder Traversal/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/binary-tree-preorder-traversal 2 | // 3 | // Given a binary tree, return the preorder traversal of its nodes' values. 4 | // 5 | // For example: 6 | // Given binary tree {1,#,2,3}, 7 | // 8 | // 1 9 | // \ 10 | // 2 11 | // / 12 | // 3 13 | // 14 | // 15 | // 16 | // return [1,2,3]. 17 | // 18 | // Note: Recursive solution is trivial, could you do it iteratively? 19 | /** 20 | * Definition for a binary tree node. 21 | * public class TreeNode { 22 | * int val; 23 | * TreeNode left; 24 | * TreeNode right; 25 | * TreeNode(int x) { val = x; } 26 | * } 27 | */ 28 | public class Solution { 29 | public List preorderTraversal(TreeNode root) { 30 | List result = new ArrayList<>(); 31 | if (root == null) return result; 32 | recursion(root, result); 33 | return result; 34 | } 35 | 36 | private void recursion(TreeNode root, List result) { 37 | if (root == null) return; 38 | result.add(root.val); 39 | recursion(root.left, result); 40 | recursion(root.right, result); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /Linked List Cycle II/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/linked-list-cycle-ii 2 | // 3 | // Given a linked list, return the node where the cycle begins. If there is no cycle, return null. 4 | // 5 | // Note: Do not modify the linked list. 6 | // 7 | // Follow up: 8 | // Can you solve it without using extra space? 9 | /** 10 | * Definition for singly-linked list. 11 | * class ListNode { 12 | * int val; 13 | * ListNode next; 14 | * ListNode(int x) { 15 | * val = x; 16 | * next = null; 17 | * } 18 | * } 19 | */ 20 | public class Solution { 21 | public ListNode detectCycle(ListNode head) { 22 | if (head == null) return null; 23 | ListNode slow = head; 24 | ListNode fast = head; 25 | while (slow != null && fast != null && fast.next != null) { 26 | slow = slow.next; 27 | fast = fast.next.next; 28 | if (slow == fast) { 29 | while (slow != head) { 30 | head = head.next; 31 | slow = slow.next; 32 | } 33 | return slow; 34 | } 35 | } 36 | return null; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Bulb Switcher/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/bulb-switcher 2 | // 3 | // 4 | // 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. 5 | // 6 | // Find how many bulbs are on after n rounds. 7 | // 8 | // 9 | // Example: 10 | // 11 | // Given n = 3. 12 | // At first, the three bulbs are [off, off, off]. 13 | // After first round, the three bulbs are [on, on, on]. 14 | // After second round, the three bulbs are [on, off, on]. 15 | // After third round, the three bulbs are [on, off, off]. 16 | // So you should return 1, because there is only one bulb is on. 17 | // 18 | public class Solution { 19 | public int bulbSwitch(int n) { 20 | if (n == 0) return 0; 21 | int step = 0; 22 | while (step * step < n) { 23 | step++; 24 | } 25 | if (Math.ceil(Math.sqrt(n)) * Math.ceil(Math.sqrt(n)) == n) { 26 | return step; 27 | } 28 | return step - 1; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Pascal-s Triangle/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/pascals-triangle 2 | // 3 | // Given numRows, generate the first numRows of Pascal's triangle. 4 | // 5 | // For example, given numRows = 5, 6 | // Return 7 | // 8 | // [ 9 | // [1], 10 | // [1,1], 11 | // [1,2,1], 12 | // [1,3,3,1], 13 | // [1,4,6,4,1] 14 | // ] 15 | // 16 | // 17 | public class Solution { 18 | public List> generate(int numRows) { 19 | List> result = new ArrayList<>(); 20 | while (numRows-- > 0) { 21 | if (result.isEmpty()) { 22 | List array = new ArrayList<>(); 23 | array.add(1); 24 | result.add(array); 25 | continue; 26 | } 27 | List previous = result.get(result.size() - 1); 28 | List current = new ArrayList<>(); 29 | current.add(1); 30 | for (int i = 1; i < previous.size(); i++) { 31 | current.add(previous.get(i - 1) + previous.get(i)); 32 | } 33 | current.add(1); 34 | result.add(current); 35 | } 36 | return result; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Remove Duplicates from Sorted List II/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii 2 | // 3 | // 4 | // Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. 5 | // 6 | // 7 | // For example, 8 | // Given 1->2->3->3->4->4->5, return 1->2->5. 9 | // Given 1->1->1->2->3, return 2->3. 10 | // 11 | /** 12 | * Definition for singly-linked list. 13 | * public class ListNode { 14 | * int val; 15 | * ListNode next; 16 | * ListNode(int x) { val = x; } 17 | * } 18 | */ 19 | public class Solution { 20 | public ListNode deleteDuplicates(ListNode head) { 21 | if (head == null) return null; 22 | ListNode dummy = new ListNode(-1); 23 | dummy.next = head; 24 | if (head.next != null && head.val == head.next.val) { 25 | while (head.next != null && head.val == head.next.val) { 26 | head.next = head.next.next; 27 | } 28 | return deleteDuplicates(head.next); 29 | } else { 30 | head.next = deleteDuplicates(head.next); 31 | } 32 | return dummy.next; 33 | 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Shortest Word Distance/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/shortest-word-distance 2 | // 3 | // Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list. 4 | // 5 | // For example, 6 | // Assume that words = ["practice", "makes", "perfect", "coding", "makes"]. 7 | // 8 | // Given word1 = “coding”, word2 = “practice”, return 3. 9 | // Given word1 = "makes", word2 = "coding", return 1. 10 | // 11 | // Note: 12 | // You may assume that word1 does not equal to word2, and word1 and word2 are both in the list. 13 | class Solution { 14 | public int shortestDistance(String[] words, String word1, String word2) { 15 | int result = Integer.MAX_VALUE; 16 | int first = Integer.MAX_VALUE; 17 | int second = Integer.MAX_VALUE; 18 | for (int i = 0; i < words.length; i++) { 19 | if (words[i].equals(word1)) first = i; 20 | if (words[i].equals(word2)) second = i; 21 | if (first != Integer.MAX_VALUE && second != Integer.MAX_VALUE) { 22 | result = Math.min(result, Math.abs(second - first)); 23 | } 24 | } 25 | return result; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Longest Substring Without Repeating Characters/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/longest-substring-without-repeating-characters 2 | // 3 | // Given a string, find the length of the longest substring without repeating characters. 4 | // Examples: 5 | // Given "abcabcbb", the answer is "abc", which the length is 3. 6 | // Given "bbbbb", the answer is "b", with the length of 1. 7 | // Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring. 8 | public class Solution { 9 | 10 | public int lengthOfLongestSubstring(String s) { 11 | if (s.length() == 0) return 0; 12 | int result = 0; 13 | int temp = 0; 14 | int[] bucket = new int[256]; 15 | for (int i = 0, k = 0; k < s.length();) { 16 | if (bucket[s.charAt(k)] == 0) { 17 | bucket[s.charAt(k)]++; 18 | k++; 19 | temp++; 20 | result = Math.max(result, temp); 21 | } else { 22 | bucket[s.charAt(i)]--; 23 | temp--; 24 | i++; 25 | } 26 | } 27 | return result; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Find the Duplicate Number/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/find-the-duplicate-number 2 | // 3 | // Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one. 4 | // 5 | // Note: 6 | // You must not modify the array (assume the array is read only). 7 | // You must use only constant, O(1) extra space. 8 | // Your runtime complexity should be less than O(n2). 9 | // There is only one duplicate number in the array, but it could be repeated more than once. 10 | // Credits: 11 | // Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases. 12 | class Solution { 13 | public int findDuplicate(int[] nums) { 14 | int slow = nums[0]; 15 | int fast = nums[nums[0]]; 16 | while (nums[slow] != nums[fast]) { 17 | slow = nums[slow]; 18 | fast = nums[nums[fast]]; 19 | } 20 | fast = 0; 21 | while (nums[slow] != nums[fast]) { 22 | slow = nums[slow]; 23 | fast = nums[fast]; 24 | } 25 | return nums[slow]; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Longest Valid Parentheses/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/longest-valid-parentheses 2 | // 3 | // Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring. 4 | // 5 | // For "(()", the longest valid parentheses substring is "()", which has length = 2. 6 | // 7 | // Another example is ")()())", where the longest valid parentheses substring is "()()", which has length = 4. 8 | class Solution { 9 | public int longestValidParentheses(String s) { 10 | int helper = 0, result = 0; 11 | char[] array = s.toCharArray(); 12 | int[] dp = new int[array.length]; 13 | for (int i = 0; i < array.length; i++) { 14 | if (array[i] == '(') { 15 | helper++; 16 | } else { 17 | if (helper != 0) { 18 | helper--; 19 | int value = Math.max(dp[i - 1], i > 2 ? dp[i - 2] : 0) + 2; 20 | value += i >= value ? dp[i - value] : 0; 21 | result = Math.max(result, value); 22 | dp[i] = value; 23 | } 24 | } 25 | } 26 | return result; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Find Peak Element/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/find-peak-element 2 | // 3 | // A peak element is an element that is greater than its neighbors. 4 | // 5 | // Given an input array where num[i] ≠ num[i+1], find a peak element and return its index. 6 | // 7 | // The array may contain multiple peaks, in that case return the index to any one of the peaks is fine. 8 | // 9 | // You may imagine that num[-1] = num[n] = -∞. 10 | // 11 | // For example, in array [1, 2, 3, 1], 3 is a peak element and your function should return the index number 2. 12 | // 13 | // click to show spoilers. 14 | // 15 | // Note: 16 | // Your solution should be in logarithmic complexity. 17 | // 18 | // Credits: 19 | // Special thanks to @ts for adding this problem and creating all test cases. 20 | class Solution { 21 | public int findPeakElement(int[] nums) { 22 | int left = 0; 23 | int right = nums.length - 1; 24 | while (left < right) { 25 | int mid = (left + right) / 2; 26 | if (nums[mid] < nums[mid + 1]) { 27 | left = mid + 1; 28 | } else { 29 | right = mid; 30 | } 31 | } 32 | return left; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Jewels and Stones/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/jewels-and-stones 2 | // 3 | // 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. 4 | // 5 | // 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". 6 | // 7 | // Example 1: 8 | // 9 | // Input: J = "aA", S = "aAAbbbb" 10 | // Output: 3 11 | // Example 2: 12 | // 13 | // Input: J = "z", S = "ZZ" 14 | // Output: 0 15 | // Note: 16 | // 17 | // S and J will consist of letters and have length at most 50. 18 | // The characters in J are distinct. 19 | class Solution { 20 | public int numJewelsInStones(String J, String S) { 21 | boolean[] jems = new boolean[256]; 22 | for (int i = 0; i < J.length(); i++) { 23 | jems[J.charAt(i)] = true; 24 | } 25 | int result = 0; 26 | for (int i = 0; i < S.length(); i++) { 27 | if (jems[S.charAt(i)]) result++; 28 | } 29 | return result; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Paint House/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/paint-house 2 | // 3 | // 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. 4 | // 5 | // 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. 6 | // 7 | // Note: 8 | // All costs are positive integers. 9 | class Solution { 10 | public int minCost(int[][] costs) { 11 | if (costs == null || costs.length == 0) return 0; 12 | int n = costs.length - 1; 13 | for (int i = 1; i <= n; i++) { 14 | costs[i][0] += Math.min(costs[i - 1][1], costs[i - 1][2]); 15 | costs[i][1] += Math.min(costs[i - 1][2], costs[i - 1][0]); 16 | costs[i][2] += Math.min(costs[i - 1][1], costs[i - 1][0]); 17 | } 18 | return Math.min(costs[n][0], Math.min(costs[n][1], costs[n][2])); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Reverse Words in a String III/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/reverse-words-in-a-string-iii 2 | // 3 | // Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order. 4 | // Example 1: 5 | // 6 | // Input: "Let's take LeetCode contest" 7 | // Output: "s'teL ekat edoCteeL tsetnoc" 8 | // 9 | // 10 | // Note: 11 | // In the string, each word is separated by single space and there will not be any extra space in the string. 12 | // 13 | public class Solution { 14 | public String reverseWords(String s) { 15 | char[] array = s.toCharArray(); 16 | int l = array.length; 17 | int i = 0; 18 | for (int k = 0; k < l; k++) { 19 | if (array[k] == ' ') { 20 | reverse(array, i, k); 21 | i = k + 1; 22 | } 23 | } 24 | reverse(array, i, l); 25 | return new String(array); 26 | } 27 | 28 | private void reverse(char[] array, int start, int end) { 29 | while (start < end){ 30 | char t = array[start]; 31 | array[start++] = array[--end]; 32 | array[end] = t; 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Two Sum IV - Input is a BST/Solution_recursive_O(n).java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/two-sum-iv-input-is-a-bst 2 | // 3 | // Given a Binary Search Tree and a target number, return true if there exist two elements in the BST such that their sum is equal to the given target. 4 | // Example 1: 5 | // 6 | // Input: 7 | // 5 8 | // / \ 9 | // 3 6 10 | // / \ \ 11 | // 2 4 7 12 | // 13 | // Target = 9 14 | // 15 | // Output: True 16 | // 17 | // 18 | // Example 2: 19 | // 20 | // Input: 21 | // 5 22 | // / \ 23 | // 3 6 24 | // / \ \ 25 | // 2 4 7 26 | // 27 | // Target = 28 28 | // 29 | // Output: False 30 | // 31 | // 32 | // 33 | /** 34 | * Definition for a binary tree node. 35 | * public class TreeNode { 36 | * int val; 37 | * TreeNode left; 38 | * TreeNode right; 39 | * TreeNode(int x) { val = x; } 40 | * } 41 | */ 42 | public class Solution { 43 | Set set = new HashSet<>(); 44 | 45 | public boolean findTarget(TreeNode root, int k) { 46 | if (root == null) return false; 47 | if (set.contains(k - root.val)) return true; 48 | set.add(root.val); 49 | return findTarget(root.left, k) || findTarget(root.right, k); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /Kth Smallest Element in a BST/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/kth-smallest-element-in-a-bst 2 | // 3 | // Given a binary search tree, write a function kthSmallest to find the kth smallest element in it. 4 | // Note: 5 | // You may assume k is always valid, 1 ? k ? BST's total elements. 6 | // Follow up: 7 | // What if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently? How would you optimize the kthSmallest routine? 8 | // Credits:Special thanks to @ts for adding this problem and creating all test cases. 9 | /** 10 | * Definition for a binary tree node. 11 | * public class TreeNode { 12 | * int val; 13 | * TreeNode left; 14 | * TreeNode right; 15 | * TreeNode(int x) { val = x; } 16 | * } 17 | */ 18 | public class Solution { 19 | Integer result, counter = null; 20 | 21 | public int kthSmallest(TreeNode root, int k) { 22 | counter = k; 23 | helper(root); 24 | return result; 25 | } 26 | 27 | private void helper(TreeNode root) { 28 | if (root == null || result != null) return; 29 | helper(root.left); 30 | if (--counter == 0) result = root.val; 31 | helper(root.right); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Longest Continuous Increasing Subsequence/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/longest-continuous-increasing-subsequence 2 | // 3 | // Given an unsorted array of integers, find the length of longest continuous increasing subsequence. 4 | // 5 | // Example 1: 6 | // Input: [1,3,5,4,7] 7 | // Output: 3 8 | // Explanation: The longest continuous increasing subsequence is [1,3,5], its length is 3. 9 | // Even though [1,3,5,7] is also an increasing subsequence, it's not a continuous one where 5 and 7 are separated by 4. 10 | // Example 2: 11 | // Input: [2,2,2,2,2] 12 | // Output: 1 13 | // Explanation: The longest continuous increasing subsequence is [2], its length is 1. 14 | // Note: Length of the array will not exceed 10,000. 15 | class Solution { 16 | public int findLengthOfLCIS(int[] nums) { 17 | int length = nums.length; 18 | if (length == 0) return length; 19 | int result = 1; 20 | int temp = 1; 21 | for (int i = 1; i < length; i++) { 22 | if (nums[i] <= nums[i - 1]) { 23 | result = Math.max(result, temp); 24 | temp = 0; 25 | } 26 | temp++; 27 | } 28 | return Math.max(result, temp); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Two Sum II - Input array is sorted/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/two-sum-ii-input-array-is-sorted 2 | // 3 | // Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number. 4 | // The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based. 5 | // You may assume that each input would have exactly one solution and you may not use the same element twice. 6 | // 7 | // Input: numbers={2, 7, 11, 15}, target=9 8 | // Output: index1=1, index2=2 9 | // 10 | public class Solution { 11 | public int[] twoSum(int[] numbers, int target) { 12 | int[] result = new int[2]; 13 | int left = 0; 14 | int right = numbers.length - 1; 15 | while(numbers[left] + numbers[right] != target) { 16 | if (numbers[left] + numbers[right] > target) { 17 | right--; 18 | } else { 19 | left++; 20 | } 21 | } 22 | result[0] = ++left; 23 | result[1] = ++right; 24 | return result; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Maximum Length of Pair Chain/Solution_nlogn.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/maximum-length-of-pair-chain/description/ 2 | // 3 | // You are given n pairs of numbers. In every pair, the first number is always smaller than the second number. 4 | // 5 | // Now, we define a pair (c, d) can follow another pair (a, b) if and only if b < c. Chain of pairs can be formed in this fashion. 6 | // 7 | // Given a set of pairs, find the length longest chain which can be formed. You needn't use up all the given pairs. You can select pairs in any order. 8 | // 9 | // Example 1: 10 | // Input: [[1,2], [2,3], [3,4]] 11 | // Output: 2 12 | // Explanation: The longest chain is [1,2] -> [3,4] 13 | // Note: 14 | // The number of given pairs will be in the range [1, 1000]. 15 | class Solution { 16 | public int findLongestChain(int[][] pairs) { 17 | Arrays.sort(pairs, Comparator.comparingInt(o -> o[1])); 18 | int length = pairs.length; 19 | int result = 1; 20 | int right = pairs[0][1]; 21 | for (int i = 1; i < length; i++) { 22 | if (right < pairs[i][0]) { 23 | right = pairs[i][1]; 24 | result++; 25 | } 26 | } 27 | return result; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Longest Palindromic Substring/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/longest-palindromic-substring 2 | // 3 | // Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000. 4 | // Example: 5 | // 6 | // Input: "babad" 7 | // 8 | // Output: "bab" 9 | // 10 | // Note: "aba" is also a valid answer. 11 | // 12 | // 13 | // Example: 14 | // 15 | // Input: "cbbd" 16 | // 17 | // Output: "bb" 18 | // 19 | // 20 | public class Solution { 21 | 22 | private int max; 23 | private int cursor; 24 | 25 | private void isPalindrome(String s, int start, int end) { 26 | while (start >= 0 && end < s.length() && s.charAt(start) == s.charAt(end)) { 27 | start--; 28 | end++; 29 | } 30 | if (max < end - start - 1) { 31 | cursor = start + 1; 32 | max = end - start - 1; 33 | } 34 | } 35 | 36 | public String longestPalindrome(String s) { 37 | if (s.length() < 2) return s; 38 | for (int i = 0; i < s.length() - 1; i++) { 39 | isPalindrome(s, i, i); 40 | isPalindrome(s, i, i + 1); 41 | } 42 | return s.substring(cursor, cursor + max); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /Longest Substring with At Most Two Distinct Characters/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters 2 | // 3 | // Given a string, find the length of the longest substring T that contains at most 2 distinct characters. 4 | // 5 | // For example, Given s = “eceba”, 6 | // 7 | // T is "ece" which its length is 3. 8 | class Solution { 9 | public int lengthOfLongestSubstringTwoDistinct(String s) { 10 | int result = 0; 11 | int[] bucket = new int[256]; 12 | int first = 0; 13 | int second = 0; 14 | char[] a = s.toCharArray(); 15 | int distincts = 0; 16 | while (second <= s.length()) { 17 | while (distincts > 2) { 18 | if (bucket[a[first]] == 1) { 19 | distincts--; 20 | } 21 | bucket[a[first]]--; 22 | first++; 23 | } 24 | result = Math.max(result, second - first); 25 | if (second == s.length()) break; 26 | if (bucket[a[second]]++ == 0) { 27 | distincts++; 28 | } 29 | second++; 30 | 31 | } 32 | return Math.max(result, distincts); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Path Sum/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/path-sum 2 | // 3 | // 4 | // Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum. 5 | // 6 | // 7 | // For example: 8 | // Given the below binary tree and sum = 22, 9 | // 10 | // 5 11 | // / \ 12 | // 4 8 13 | // / / \ 14 | // 11 13 4 15 | // / \ \ 16 | // 7 2 1 17 | // 18 | // 19 | // return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22. 20 | /** 21 | * Definition for a binary tree node. 22 | * public class TreeNode { 23 | * int val; 24 | * TreeNode left; 25 | * TreeNode right; 26 | * TreeNode(int x) { val = x; } 27 | * } 28 | */ 29 | public class Solution { 30 | public boolean hasPathSum(TreeNode root, int sum) { 31 | if (root == null) return false; 32 | if (root.left == null && root.right == null && sum - root.val== 0) return true; 33 | boolean left = hasPathSum(root.left, sum - root.val); 34 | boolean right = hasPathSum(root.right, sum - root.val); 35 | return left == true || right == true; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /Set Matrix Zeroes/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/set-matrix-zeroes 2 | // 3 | // 4 | // Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place. 5 | // 6 | // click to show follow up. 7 | // Follow up: 8 | // 9 | // Did you use extra space? 10 | // A straight forward solution using O(mn) space is probably a bad idea. 11 | // A simple improvement uses O(m + n) space, but still not the best solution. 12 | // Could you devise a constant space solution? 13 | // 14 | // 15 | public class Solution { 16 | public void setZeroes(int[][] matrix) { 17 | int rows = matrix.length; 18 | int columns = matrix[0].length; 19 | boolean[] x = new boolean[rows]; 20 | boolean[] y = new boolean[columns]; 21 | for (int i = 0; i < rows; i++) { 22 | for (int k = 0; k < columns; k++) { 23 | if (matrix[i][k] == 0) { 24 | x[i] = true; 25 | y[k] = true; 26 | } 27 | } 28 | } 29 | for (int i = 0; i < rows; i++) { 30 | for (int k = 0; k < columns; k++) { 31 | if (x[i] || y[k]) matrix[i][k] = 0; 32 | } 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Valid Parentheses/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/valid-parentheses 2 | // 3 | // Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. 4 | // The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not. 5 | // 6 | public class Solution { 7 | public boolean isValid(String s) { 8 | Stack stack = new Stack<>(); 9 | char[] chars = s.toCharArray(); 10 | for (int i = 0; i < chars.length; i++) { 11 | if (chars[i] == '(' || chars[i] == '[' || chars[i] == '{') { 12 | stack.add(chars[i]); 13 | } else { 14 | if (stack.empty()) { 15 | return false; 16 | } 17 | char temp = stack.pop(); 18 | if (temp == '[' && chars[i] != ']') { 19 | return false; 20 | } else if (temp == '{' && chars[i] != '}') { 21 | return false; 22 | } else if (temp == '(' && chars[i] != ')') { 23 | return false; 24 | } 25 | } 26 | } 27 | return stack.empty(); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Longest Valid Parentheses/solution.py: -------------------------------------------------------------------------------- 1 | """" 2 | https://leetcode.com/problems/longest-valid-parentheses 3 | 4 | Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring. 5 | 6 | For "(()", the longest valid parentheses substring is "()", which has length = 2. 7 | 8 | Another example is ")()())", where the longest valid parentheses substring is "()()", which has length = 4. 9 | """ 10 | class Solution(object): 11 | def longestValidParentheses(self, s): 12 | """ 13 | :type s: str 14 | :rtype: int 15 | """ 16 | result = 0 17 | stack = [] 18 | d = {} 19 | for position, bracket in enumerate(s): 20 | if bracket == '(': 21 | stack.append(bracket) 22 | if bracket == ')': 23 | if not stack: 24 | continue 25 | if stack[-1] == '(': 26 | stack.pop() 27 | value = max(d.get(position - 1, 0), d.get(position - 2, 0)) + 2 28 | value += d.get(position - value, 0) 29 | result = max(result, value) 30 | d[position] = value 31 | return result 32 | -------------------------------------------------------------------------------- /Reverse Linked List II/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/reverse-linked-list-ii 2 | // 3 | // Reverse a linked list from position m to n. Do it in-place and in one-pass. 4 | // 5 | // For example: 6 | // Given 1->2->3->4->5->NULL, m = 2 and n = 4, 7 | // 8 | // return 1->4->3->2->5->NULL. 9 | // 10 | // Note: 11 | // Given m, n satisfy the following condition: 12 | // 1 ≤ m ≤ n ≤ length of list. 13 | /** 14 | * Definition for singly-linked list. 15 | * public class ListNode { 16 | * int val; 17 | * ListNode next; 18 | * ListNode(int x) { val = x; } 19 | * } 20 | */ 21 | public class Solution { 22 | public ListNode reverseBetween(ListNode head, int m, int n) { 23 | if (n == m) return head; 24 | ListNode dummy = new ListNode(0); 25 | dummy.next = head; 26 | ListNode cursor = dummy; 27 | n -= m; 28 | while (m-- > 1) cursor = cursor.next; 29 | ListNode left = cursor.next; 30 | ListNode helper = left.next; 31 | while (n-- > 0) { 32 | left.next = helper.next; 33 | helper.next = cursor.next; 34 | cursor.next = helper; 35 | helper = left.next; 36 | } 37 | return dummy.next; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Search a 2D Matrix/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/search-a-2d-matrix 2 | // 3 | // Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: 4 | // 5 | // Integers in each row are sorted from left to right. 6 | // The first integer of each row is greater than the last integer of the previous row. 7 | // For example, 8 | // 9 | // Consider the following matrix: 10 | // 11 | // [ 12 | // [1, 3, 5, 7], 13 | // [10, 11, 16, 20], 14 | // [23, 30, 34, 50] 15 | // ] 16 | // Given target = 3, return true. 17 | class Solution { 18 | public boolean searchMatrix(int[][] matrix, int target) { 19 | int y = matrix.length; 20 | if (y == 0) return false; 21 | int x = matrix[0].length; 22 | if (x == 0) return false; 23 | int left = 0; 24 | int right = x * y; 25 | while (left <= right) { 26 | int mid = left + (right - left) / 2; 27 | if (mid / x == y) return false; 28 | if (matrix[mid / x][mid % x] == target) return true; 29 | else if (matrix[mid / x][mid % x] > target) right = mid - 1; 30 | else left = mid + 1; 31 | } 32 | return false; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Single Number III/solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://leetcode.com/problems/single-number-iii 3 | 4 | Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. 5 | 6 | For example: 7 | 8 | Given nums = [1, 2, 1, 3, 2, 5], return [3, 5]. 9 | 10 | Note: 11 | The order of the result is not important. So in the above example, [5, 3] is also correct. 12 | Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity? 13 | Credits: 14 | Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases. 15 | """ 16 | class Solution(object): 17 | def singleNumber(self, nums): 18 | """ 19 | :type nums: List[int] 20 | :rtype: List[int] 21 | """ 22 | first = second = xor_of_two_numbers = 0 23 | for i in nums: 24 | xor_of_two_numbers ^= i 25 | last_setted_bit_position = xor_of_two_numbers & -xor_of_two_numbers 26 | for i in nums: 27 | if last_setted_bit_position & -i == 0: 28 | first ^= i 29 | else: 30 | second ^= i 31 | return [first, second] 32 | -------------------------------------------------------------------------------- /Subsets II/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/subsets-ii 2 | // 3 | // 4 | // Given a collection of integers that might contain duplicates, nums, return all possible subsets. 5 | // 6 | // Note: The solution set must not contain duplicate subsets. 7 | // 8 | // 9 | // For example, 10 | // If nums = [1,2,2], a solution is: 11 | // 12 | // 13 | // [ 14 | // [2], 15 | // [1], 16 | // [1,2,2], 17 | // [2,2], 18 | // [1,2], 19 | // [] 20 | // ] 21 | // 22 | public class Solution { 23 | public List> subsetsWithDup(int[] nums) { 24 | List> result = new ArrayList<>(); 25 | Arrays.sort(nums); 26 | backtrack(nums, 0, new ArrayList<>(), result); 27 | return result; 28 | } 29 | 30 | private void backtrack(int[] candidates, int current, List temp, List> result) { 31 | for (int i = current; i < candidates.length; i++) { 32 | if (i > current && candidates[i] == candidates[i - 1]) continue; 33 | temp.add(candidates[i]); 34 | backtrack(candidates, i + 1, temp, result); 35 | temp.remove(temp.size() - 1); 36 | 37 | } 38 | result.add(new ArrayList<>(temp)); 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /Non-decreasing Array/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/non-decreasing-array/ 2 | // Given an array with n integers, your task is to check if it could become non-decreasing by modifying at most 1 element. 3 | // 4 | // We define an array is non-decreasing if array[i] <= array[i + 1] holds for every i (1 <= i < n). 5 | // 6 | // Example 1: 7 | // Input: [4,2,3] 8 | // Output: True 9 | // Explanation: You could modify the first 10 | // 4 11 | // to 12 | // 1 13 | // to get a non-decreasing array. 14 | // Example 2: 15 | // Input: [4,2,1] 16 | // Output: False 17 | // Explanation: You can't get a non-decreasing array by modify at most one element. 18 | // Note: The n belongs to [1, 10,000]. 19 | 20 | class Solution { 21 | public boolean checkPossibility(int[] nums) { 22 | boolean tricked = false; 23 | for (int i = 1; i < nums.length; i++) { 24 | if (nums[i - 1] > nums[i]) { 25 | if (tricked) return false; 26 | else { 27 | if (i > 1 && nums[i] < nums[i - 2]) { 28 | nums[i] = nums[i - 1]; 29 | } 30 | tricked = true; 31 | } 32 | } 33 | } 34 | return true; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Binary Tree Postorder Traversal/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/binary-tree-postorder-traversal 2 | // 3 | // Given a binary tree, return the postorder traversal of its nodes' values. 4 | // 5 | // For example: 6 | // Given binary tree {1,#,2,3}, 7 | // 8 | // 1 9 | // \ 10 | // 2 11 | // / 12 | // 3 13 | // 14 | // 15 | // 16 | // return [3,2,1]. 17 | // 18 | // Note: Recursive solution is trivial, could you do it iteratively? 19 | /** 20 | * Definition for a binary tree node. 21 | * public class TreeNode { 22 | * int val; 23 | * TreeNode left; 24 | * TreeNode right; 25 | * TreeNode(int x) { val = x; } 26 | * } 27 | */ 28 | public class Solution { 29 | public List postorderTraversal(TreeNode root) { 30 | List result = new ArrayList<>(); 31 | if (root == null) return result; 32 | Deque deque = new LinkedList<>(); 33 | deque.push(root); 34 | while (!deque.isEmpty()) { 35 | TreeNode temp = deque.poll(); 36 | result.add(0, temp.val); 37 | if (temp.left != null) deque.push(temp.left); 38 | if (temp.right != null) deque.push(temp.right); 39 | } 40 | return result; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /House Robber/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/house-robber 2 | // 3 | // 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. 4 | // 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. 5 | // Credits:Special thanks to @ifanchu for adding this problem and creating all test cases. Also thanks to @ts for adding additional test cases. 6 | public class Solution { 7 | public int rob(int[] nums) { 8 | int length = nums.length; 9 | if (length == 0) return 0; 10 | if (length == 1) return nums[0]; 11 | if (length == 2) return Math.max(nums[0], nums[1]); 12 | for (int i = 2; i < length; i++) { 13 | nums[i] = Math.max(nums[i - 2] + nums[i], nums[i - 1]); 14 | nums[i - 1] = Math.max(nums[i - 1], nums[i - 2]); 15 | } 16 | return Math.max(nums[length - 1], nums[length - 2]); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Largest Rectangle in Histogram/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/largest-rectangle-in-histogram 2 | // 3 | // Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram. 4 | // 5 | // 6 | // Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3]. 7 | // 8 | // 9 | // The largest rectangle is shown in the shaded area, which has area = 10 unit. 10 | // 11 | // For example, 12 | // Given heights = [2,1,5,6,2,3], 13 | // return 10. 14 | class Solution { 15 | public int largestRectangleArea(int[] heights) { 16 | int result = 0; 17 | Deque deque = new LinkedList<>(); 18 | for (int i = 0; i <= heights.length; i++) { 19 | int h = i == heights.length ? 0 : heights[i]; 20 | if (deque.isEmpty() || h > heights[deque.peek()]) { 21 | deque.push(i); 22 | } else { 23 | int height = heights[deque.pop()]; 24 | int width = deque.isEmpty() ? i : i - deque.peek() - 1; 25 | result = Math.max(result, height * width); 26 | i--; 27 | } 28 | } 29 | return result; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Valid Mountain Array/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/valid-mountain-array/description/ 2 | // 3 | // Given an array A of integers, return true if and only if it is a valid mountain array. 4 | // 5 | // Recall that A is a mountain array if and only if: 6 | // 7 | // A.length >= 3 8 | // There exists some i with 0 < i < A.length - 1 such that: 9 | // A[0] < A[1] < ... A[i-1] < A[i] 10 | // A[i] > A[i+1] > ... > A[B.length - 1] 11 | // 12 | // 13 | // Example 1: 14 | // 15 | // Input: [2,1] 16 | // Output: false 17 | // Example 2: 18 | // 19 | // Input: [3,5,5] 20 | // Output: false 21 | // Example 3: 22 | // 23 | // Input: [0,3,2,1] 24 | // Output: true 25 | // 26 | // 27 | // Note: 28 | // 29 | // 0 <= A.length <= 10000 30 | // 0 <= A[i] <= 10000 31 | class Solution { 32 | public boolean validMountainArray(int[] A) { 33 | if (A.length < 3) return false; 34 | int left = 0; 35 | int right = A.length - 1; 36 | while (left < A.length - 1 && A[left] < A[left + 1]) { 37 | left++; 38 | } 39 | if (left == 0 || left == right) return false; 40 | while (right >= left && A[right] < A[right - 1]) { 41 | right--; 42 | } 43 | return right == left; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /Longest Substring with At Most K Distinct Characters/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/longest-substring-with-at-most-k-distinct-characters 2 | // 3 | // Given a string, find the length of the longest substring T that contains at most k distinct characters. 4 | // 5 | // For example, Given s = “eceba” and k = 2, 6 | // 7 | // T is "ece" which its length is 3. 8 | class Solution { 9 | public int lengthOfLongestSubstringKDistinct(String s, int k) { 10 | int result = 0; 11 | Map map = new HashMap<>(); 12 | int first = 0; 13 | int second = 0; 14 | char[] a = s.toCharArray(); 15 | while (second <= s.length()) { 16 | while (map.size() > k) { 17 | if (map.get(a[first]) == 1) { 18 | map.remove(a[first]); 19 | } else { 20 | map.put(a[first], map.get(a[first]) - 1); 21 | } 22 | first++; 23 | } 24 | result = Math.max(result, second - first); 25 | if (second == s.length()) break; 26 | map.put(a[second], map.getOrDefault(a[second], 0) + 1); 27 | second++; 28 | 29 | } 30 | return Math.max(result, 0); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Minimum Moves to Equal Array Elements II/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/minimum-moves-to-equal-array-elements-ii 2 | // 3 | // Given a non-empty integer array, find the minimum number of moves required to make all array elements equal, where a move is incrementing a selected element by 1 or decrementing a selected element by 1. 4 | // You may assume the array's length is at most 10,000. 5 | // Example: 6 | // 7 | // Input: 8 | // [1,2,3] 9 | // 10 | // Output: 11 | // 2 12 | // 13 | // Explanation: 14 | // Only two moves are needed (remember each move increments or decrements one element): 15 | // 16 | // [1,2,3] => [2,2,3] => [2,2,2] 17 | // 18 | // 19 | public class Solution { 20 | public int minMoves2(int[] nums) { 21 | int medium; 22 | int summ = 0; 23 | int moves = 0; 24 | Arrays.sort(nums); 25 | int middle = nums.length/2; 26 | if (nums.length%2 == 1) { 27 | medium = nums[middle]; 28 | } else { 29 | medium = (nums[middle-1] + nums[middle]) / 2; 30 | } 31 | System.out.println(medium); 32 | for (int i = 0; i < nums.length; i++) { 33 | 34 | moves += Math.abs(nums[i] - medium); 35 | } 36 | return moves; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Convert BST to Greater Tree/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/convert-bst-to-greater-tree 2 | // 3 | // Given a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus sum of all keys greater than the original key in BST. 4 | // 5 | // Example: 6 | // 7 | // Input: The root of a Binary Search Tree like this: 8 | // 5 9 | // / \ 10 | // 2 13 11 | // 12 | // Output: The root of a Greater Tree like this: 13 | // 18 14 | // / \ 15 | // 20 13 16 | // 17 | // 18 | /** 19 | * Definition for a binary tree node. 20 | * public class TreeNode { 21 | * int val; 22 | * TreeNode left; 23 | * TreeNode right; 24 | * TreeNode(int x) { val = x; } 25 | * } 26 | */ 27 | public class Solution { 28 | int sum = 0; 29 | 30 | public TreeNode convertBST(TreeNode root) { 31 | if (root == null) return root; 32 | helper(root); 33 | return root; 34 | } 35 | 36 | private void helper(TreeNode root) { 37 | if (root == null) return; 38 | helper(root.right); 39 | sum += root.val; 40 | root.val = sum; 41 | helper(root.left); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /Maximum Average Subarray I/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/maximum-average-subarray-i 2 | // 3 | // Given an array consisting of n integers, find the contiguous subarray of given length k that has the maximum average value. And you need to output the maximum average value. 4 | // 5 | // Example 1: 6 | // Input: [1,12,-5,-6,50,3], k = 4 7 | // Output: 12.75 8 | // Explanation: Maximum average is (12-5-6+50)/4 = 51/4 = 12.75 9 | // Note: 10 | // 1 <= k <= n <= 30,000. 11 | // Elements of the given array will be in the range [-10,000, 10,000]. 12 | class Solution { 13 | public double findMaxAverage(int[] nums, int k) { 14 | if (nums.length == 0) return 0; 15 | if (nums.length == 1) return nums[0]; 16 | double result = Integer.MIN_VALUE; 17 | int left = 0; 18 | int right = 0; 19 | double sum = 0; 20 | while (right < nums.length) { 21 | if (right < k) { 22 | sum += nums[right]; 23 | } else { 24 | result = Math.max(sum / k, result); 25 | sum += nums[right]; 26 | sum -= nums[left]; 27 | left++; 28 | } 29 | right++; 30 | } 31 | return Math.max(sum / k, result); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Find Minimum in Rotated Sorted Array II/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii 2 | // 3 | // 4 | // Follow up for "Find Minimum in Rotated Sorted Array": 5 | // What if duplicates are allowed? 6 | // Would this affect the run-time complexity? How and why? 7 | // 8 | // Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. 9 | // (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). 10 | // Find the minimum element. 11 | // The array may contain duplicates. 12 | public class Solution { 13 | public int findMin(int[] nums) { 14 | if (nums.length == 0) return -1; 15 | if (nums.length == 1) return nums[0]; 16 | if (nums.length == 2) return Math.min(nums[0], nums[1]); 17 | int left = 0; 18 | int right = nums.length - 1; 19 | int mid = 0; 20 | while (left < right) { 21 | mid = left + (right - left) / 2; 22 | if (nums[mid] > nums[right]) { 23 | left = mid + 1; 24 | } 25 | else if (nums[mid] < nums[right]) { 26 | right = mid; 27 | } 28 | else { 29 | right--; 30 | } 31 | } 32 | return nums[left]; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Min Cost Climbing Stairs/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/min-cost-climbing-stairs 2 | // 3 | // On a staircase, the i-th step has some non-negative cost cost[i] assigned (0 indexed). 4 | // 5 | // 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. 6 | // 7 | // Example 1: 8 | // Input: cost = [10, 15, 20] 9 | // Output: 15 10 | // Explanation: Cheapest is start on cost[1], pay that cost and go to the top. 11 | // Example 2: 12 | // Input: cost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1] 13 | // Output: 6 14 | // Explanation: Cheapest is start on cost[0], and only step on 1s, skipping cost[3]. 15 | // Note: 16 | // cost will have a length in the range [2, 1000]. 17 | // Every cost[i] will be an integer in the range [0, 999]. 18 | class Solution { 19 | public int minCostClimbingStairs(int[] cost) { 20 | int length = cost.length; 21 | for (int i = 0; i < length - 2; i++) { 22 | cost[i + 1] += Math.min(cost[i + 2], i < length - 2 ? 0 : cost[i + 3]); 23 | cost[i + 2] += Math.min(cost[i], cost[i + 1]); 24 | } 25 | return Math.min(cost[length - 2], cost[length - 1]); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Delete Operation for Two Strings/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/delete-operation-for-two-strings 2 | // 3 | // 4 | // Given two words word1 and word2, find the minimum number of steps required to make word1 and word2 the same, where in each step you can delete one character in either string. 5 | // 6 | // Example 1: 7 | // 8 | // Input: "sea", "eat" 9 | // Output: 2 10 | // Explanation: You need one step to make "sea" to "ea" and another step to make "eat" to "ea". 11 | // 12 | // 13 | // Note: 14 | // 15 | // The length of given words won't exceed 500. 16 | // Characters in given words can only be lower-case letters. 17 | // 18 | // 19 | public class Solution { 20 | public int minDistance(String word1, String word2) { 21 | int w1l = word1.length(); 22 | int w2l = word2.length(); 23 | if (w1l == 0) return w2l; 24 | if (w2l == 0) return w1l; 25 | int dp[][] = new int[w1l + 1][w2l + 1]; 26 | for (int i = 1; i <= w1l; i++) { 27 | for (int j = 1; j <= w2l; j++) { 28 | dp[i][j] = (word1.charAt(i-1) == word2.charAt(j-1)) ? dp[i-1][j-1] + 1 29 | : Math.max(dp[i-1][j], dp[i][j-1]); 30 | } 31 | } 32 | return w1l + w2l - dp[w1l][w2l] * 2; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Subarray Product Less Than K/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/subarray-product-less-than-k 2 | // 3 | // Your are given an array of positive integers nums. 4 | // 5 | // Count and print the number of (contiguous) subarrays where the product of all the elements in the subarray is less than k. 6 | // 7 | // Example 1: 8 | // Input: nums = [10, 5, 2, 6], k = 100 9 | // Output: 8 10 | // Explanation: The 8 subarrays that have product less than 100 are: [10], [5], [2], [6], [10, 5], [5, 2], [2, 6], [5, 2, 6]. 11 | // Note that [10, 5, 2] is not included as the product of 100 is not strictly less than k. 12 | // Note: 13 | // 14 | // 0 < nums.length <= 50000. 15 | // 0 < nums[i] < 1000. 16 | // 0 <= k < 10^6. 17 | class Solution { 18 | public int numSubarrayProductLessThanK(int[] nums, int k) { 19 | int length = nums.length; 20 | int left = 0; 21 | int right = -1; 22 | int product = 1; 23 | int result = 0; 24 | while (++right < length && k >= 2) { 25 | product *= nums[right]; 26 | while (product >= k && left < length) { 27 | product /= nums[left]; 28 | left++; 29 | } 30 | result += right - left + 1; 31 | } 32 | return result; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Word Break/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/word-break 2 | // 3 | // 4 | // 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. 5 | // 6 | // For example, given 7 | // s = "leetcode", 8 | // dict = ["leet", "code"]. 9 | // 10 | // 11 | // Return true because "leetcode" can be segmented as "leet code". 12 | // 13 | // 14 | // UPDATE (2017/1/4): 15 | // The wordDict parameter had been changed to a list of strings (instead of a set of strings). Please reload the code definition to get the latest changes. 16 | // 17 | public class Solution { 18 | public boolean wordBreak(String s, List wordDict) { 19 | int length = s.length(); 20 | if (length == 0) return true; 21 | boolean[] dp = new boolean[length + 1]; 22 | dp[0] = true; 23 | for (int i = 0; i < length; i++) { 24 | for (int j = i + 1; j <= length; j++) { 25 | if (wordDict.contains(s.substring(i, j)) && dp[i]) { 26 | dp[j] = true; 27 | } 28 | } 29 | } 30 | return dp[length]; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Best Time to Buy and Sell Stock/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/best-time-to-buy-and-sell-stock 2 | // 3 | // Say you have an array for which the ith element is the price of a given stock on day i. 4 | // 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. 5 | // Example 1: 6 | // 7 | // Input: [7, 1, 5, 3, 6, 4] 8 | // Output: 5 9 | // 10 | // max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price) 11 | // 12 | // 13 | // Example 2: 14 | // 15 | // Input: [7, 6, 4, 3, 1] 16 | // Output: 0 17 | // 18 | // In this case, no transaction is done, i.e. max profit = 0. 19 | // 20 | // 21 | public class Solution { 22 | public int maxProfit(int[] prices) { 23 | if (prices.length == 0 || prices.length == 1) return 0; 24 | int result = 0; 25 | int min = prices[0]; 26 | for (int i = 1; i < prices.length; i++) { 27 | if (prices[i - 1] > prices[i]) { 28 | if (prices[i] < min) { 29 | min = prices[i]; 30 | } 31 | } 32 | if (prices[i] - min > result) result = prices[i] - min; 33 | } 34 | return result; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /DI String Match/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/di-string-match/description/ 2 | // 3 | // Given a string S that only contains "I" (increase) or "D" (decrease), let N = S.length. 4 | // 5 | // Return any permutation A of [0, 1, ..., N] such that for all i = 0, ..., N-1: 6 | // 7 | // If S[i] == "I", then A[i] < A[i+1] 8 | // If S[i] == "D", then A[i] > A[i+1] 9 | // 10 | // 11 | // Example 1: 12 | // 13 | // Input: "IDID" 14 | // Output: [0,4,1,3,2] 15 | // Example 2: 16 | // 17 | // Input: "III" 18 | // Output: [0,1,2,3] 19 | // Example 3: 20 | // 21 | // Input: "DDI" 22 | // Output: [3,2,0,1] 23 | // 24 | // 25 | // Note: 26 | // 27 | // 1 <= S.length <= 10000 28 | // S only contains characters "I" or "D". 29 | class Solution { 30 | public int[] diStringMatch(String S) { 31 | int[] result = new int[S.length() + 1]; 32 | Arrays.fill(result, -1); 33 | int counter = 0; 34 | for (int i = 0; i < S.length(); i++) { 35 | if (S.charAt(i) == 'I') { 36 | result[i] = counter++; 37 | } 38 | } 39 | for (int i = S.length(); i >= 0; i--) { 40 | if (result[i] == -1) { 41 | result[i] = counter++; 42 | } 43 | } 44 | return result; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /Longest Harmonious Subsequence/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/longest-harmonious-subsequence 2 | // 3 | // We define a harmonious array is an array where the difference between its maximum value and its minimum value is exactly 1. 4 | // Now, given an integer array, you need to find the length of its longest harmonious subsequence among all its possible subsequences. 5 | // Example 1: 6 | // 7 | // Input: [1,3,2,2,5,2,3,7] 8 | // Output: 5 9 | // Explanation: The longest harmonious subsequence is [3,2,2,2,3]. 10 | // 11 | // 12 | // Note: 13 | // The length of the input array will not exceed 20,000. 14 | // 15 | // 16 | public class Solution { 17 | public int findLHS(int[] nums) { 18 | int result = 0; 19 | HashMap map = new HashMap<>(); 20 | for (int i : nums) { 21 | Integer temp = map.get(i); 22 | if (temp == null) { 23 | map.put(i, 1); 24 | } else { 25 | map.put(i, temp + 1); 26 | } 27 | } 28 | for (int i : nums) { 29 | Integer t1 = map.get(i); 30 | Integer t2 = map.get(i + 1); 31 | if (t1 != null && t2 != null) result = Math.max(result, t1 + t2); 32 | } 33 | return result; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Range Sum Query - Immutable/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/range-sum-query-immutable 2 | // 3 | // Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive. 4 | // Example: 5 | // 6 | // Given nums = [-2, 0, 3, -5, 2, -1] 7 | // 8 | // sumRange(0, 2) -> 1 9 | // sumRange(2, 5) -> -1 10 | // sumRange(0, 5) -> -3 11 | // 12 | // 13 | // Note: 14 | // 15 | // You may assume that the array does not change. 16 | // There are many calls to sumRange function. 17 | // 18 | // 19 | public class NumArray { 20 | 21 | private int summ = 0; 22 | private int[] array; 23 | 24 | public NumArray(int[] nums) { 25 | array = nums; 26 | for(int i: array) { 27 | summ += i; 28 | } 29 | } 30 | 31 | public int sumRange(int i, int j) { 32 | int result = summ; 33 | for(int l = 0; l < i; l++) { 34 | result -= array[l]; 35 | } 36 | 37 | for(int r = array.length - 1; r > j; r--) { 38 | result -= array[r]; 39 | } 40 | return result; 41 | } 42 | } 43 | 44 | /** 45 | * Your NumArray object will be instantiated and called as such: 46 | * NumArray obj = new NumArray(nums); 47 | * int param_1 = obj.sumRange(i,j); 48 | */ 49 | -------------------------------------------------------------------------------- /Sort List/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/sort-list 2 | // 3 | // Sort a linked list in O(n log n) time using constant space complexity. 4 | /** 5 | * Definition for singly-linked list. 6 | * public class ListNode { 7 | * int val; 8 | * ListNode next; 9 | * ListNode(int x) { val = x; } 10 | * } 11 | */ 12 | class Solution { 13 | public ListNode sortList(ListNode head) { 14 | if (head == null) return null; 15 | if (head.next == null) return head; 16 | ListNode pre = head; 17 | ListNode slow = head; 18 | ListNode fast = head; 19 | while (fast != null && fast.next != null) { 20 | pre = slow; 21 | slow = slow.next; 22 | fast = fast.next.next; 23 | } 24 | pre.next = null; 25 | return merge(sortList(head), sortList(slow)); 26 | } 27 | 28 | private ListNode merge(ListNode first, ListNode second) { 29 | if (first == null) return second; 30 | if (second == null) return first; 31 | if (first.val < second.val) { 32 | first.next = merge(first.next, second); 33 | return first; 34 | } else { 35 | second.next = merge(first, second.next); 36 | return second; 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Reverse Linked List/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/reverse-linked-list 2 | // 3 | // Reverse a singly linked list. 4 | // click to show more hints. 5 | // Hint: 6 | // A linked list can be reversed either iteratively or recursively. Could you implement both? 7 | // 8 | /** 9 | * Definition for singly-linked list. 10 | * public class ListNode { 11 | * int val; 12 | * ListNode next; 13 | * ListNode(int x) { val = x; } 14 | * } 15 | */ 16 | public class Solution { 17 | public ListNode reverseList(ListNode head) { 18 | if (head == null) return head; 19 | if (head.next == null) return head; 20 | if (head.next.next == null) { 21 | ListNode temp = head; 22 | head = head.next; 23 | head.next = temp; 24 | head.next.next = null; 25 | return head; 26 | } 27 | ListNode back = head; 28 | ListNode mid = back.next; 29 | ListNode front = mid.next; 30 | back.next = null; 31 | while (front != null) { 32 | mid.next = back; 33 | ListNode temp = front.next; 34 | front.next = mid; 35 | back = mid; 36 | mid = front; 37 | front = temp; 38 | } 39 | return mid; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /Toeplitz Matrix/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/toeplitz-matrix 2 | // 3 | // A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same element. 4 | // 5 | // Now given an M x N matrix, return True if and only if the matrix is Toeplitz. 6 | // 7 | // 8 | // Example 1: 9 | // 10 | // Input: matrix = [[1,2,3,4],[5,1,2,3],[9,5,1,2]] 11 | // Output: True 12 | // Explanation: 13 | // 1234 14 | // 5123 15 | // 9512 16 | // 17 | // In the above grid, the diagonals are "[9]", "[5, 5]", "[1, 1, 1]", "[2, 2, 2]", "[3, 3]", "[4]", and in each diagonal all elements are the same, so the answer is True. 18 | // Example 2: 19 | // 20 | // Input: matrix = [[1,2],[2,2]] 21 | // Output: False 22 | // Explanation: 23 | // The diagonal "[1, 2]" has different elements. 24 | // Note: 25 | // 26 | // matrix will be a 2D array of integers. 27 | // matrix will have a number of rows and columns in range [1, 20]. 28 | // matrix[i][j] will be integers in range [0, 99]. 29 | class Solution { 30 | public boolean isToeplitzMatrix(int[][] matrix) { 31 | for (int x = matrix[0].length, i = x + 1; i < matrix.length * x; i++) { 32 | if (i % x != 0 && matrix[i / x - 1][i % x - 1] != matrix[i / x][i % x]) return false; 33 | } 34 | return true; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /N-ary Tree Preorder Traversal/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/n-ary-tree-preorder-traversal/description/ 2 | // 3 | // Given an n-ary tree, return the preorder traversal of its nodes' values. 4 | // 5 | // 6 | // For example, given a 3-ary tree: 7 | // 8 | // 9 | // 10 | // 11 | // Return its preorder traversal as: [1,3,5,6,2,4]. 12 | // 13 | // 14 | // Note: Recursive solution is trivial, could you do it iteratively? 15 | /* 16 | // Definition for a Node. 17 | class Node { 18 | public int val; 19 | public List children; 20 | 21 | public Node() {} 22 | 23 | public Node(int _val,List _children) { 24 | val = _val; 25 | children = _children; 26 | } 27 | }; 28 | */ 29 | class Solution { 30 | public List preorder(Node root) { 31 | List result = new ArrayList<>(); 32 | Deque deque = new LinkedList<>(); 33 | if (root == null) return result; 34 | deque.push(root); 35 | while(!deque.isEmpty()) { 36 | Node current = deque.pop(); 37 | result.add(current.val); 38 | for (int i = current.children.size() - 1; i >= 0; i--) { 39 | deque.push(current.children.get(i)); 40 | } 41 | } 42 | return result; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /3-divisible Pairs/Solution.java: -------------------------------------------------------------------------------- 1 | // https://csacademy.com/contest/interview-archive/task/3-divisible-pairs/statement/ 2 | // 3 | // You are given an array of NN positive integers. Compute the number of pairs of integers in the array that have the sum divisible by 33. 4 | // 5 | // Standard input 6 | // The first line contains one integer NN. 7 | // 8 | // The second line contains NN integers representing the elements of the array. 9 | // 10 | // Standard output 11 | // Output a single number representing the number of pairs that have the sum divisible by 33. 12 | // 13 | // Input Output 14 | // 5 15 | // 1 4 2 3 3 16 | // 3 17 | // 4 18 | // 3 3 3 6 19 | // 6 20 | // 8 21 | // 1 1 7 2 11 3 6 9 22 | // 9 23 | // Don't place your source in a package 24 | import java.util.*; 25 | import java.lang.*; 26 | import java.io.*; 27 | 28 | public class Main { 29 | 30 | public static void main(String[] args) { 31 | Scanner scan = new Scanner(System.in); 32 | int values = scan.nextInt(); 33 | long result = 0; 34 | int[] helper = new int[3]; 35 | while (values-- > 0) { 36 | int i = scan.nextInt(); 37 | int m = i % 3; 38 | result += helper[(3 - m) % 3]; 39 | helper[m]++; 40 | } 41 | System.out.println(result); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /Letter Case Permutation/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/letter-case-permutation 2 | // 3 | // Given a string S, we can transform every letter individually to be lowercase or uppercase to create another string. Return a list of all possible strings we could create. 4 | // 5 | // Examples: 6 | // Input: S = "a1b2" 7 | // Output: ["a1b2", "a1B2", "A1b2", "A1B2"] 8 | // 9 | // Input: S = "3z4" 10 | // Output: ["3z4", "3Z4"] 11 | // 12 | // Input: S = "12345" 13 | // Output: ["12345"] 14 | // Note: 15 | // 16 | // S will be a string with length at most 12. 17 | // S will consist only of letters or digits. 18 | class Solution { 19 | public List letterCasePermutation(String S) { 20 | List result = new ArrayList<>(); 21 | dfs(S.toCharArray(), 0, result); 22 | return result; 23 | } 24 | 25 | private void dfs(char[] s, int start, List result) { 26 | result.add(new String(s)); 27 | for (int i = start; i < s.length; i++) { 28 | char c = s[i]; 29 | if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z') { 30 | s[i] += c > 'Z' ? 'A' - 'a' : -('A' - 'a'); 31 | dfs(s, i + 1, result); 32 | s[i] -= c > 'Z' ? 'A' - 'a' : -('A' - 'a'); 33 | } 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Maximal Square/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/maximal-square 2 | // 3 | // Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area. 4 | // 5 | // For example, given the following matrix: 6 | // 7 | // 1 0 1 0 0 8 | // 1 0 1 1 1 9 | // 1 1 1 1 1 10 | // 1 0 0 1 0 11 | // Return 4. 12 | // Credits: 13 | // Special thanks to @Freezen for adding this problem and creating all test cases. 14 | class Solution { 15 | public int maximalSquare(char[][] matrix) { 16 | int rows = matrix.length; 17 | if (rows == 0) return 0; 18 | int columns = matrix[0].length; 19 | int result = 0; 20 | for (int i = 0; i < rows; i++) { 21 | for (int j = 0; j < columns; j++) { 22 | if (matrix[i][j] == '1') { 23 | int left = j > 0 ? matrix[i][j - 1] - '0' : 0; 24 | int top = i > 0 ? matrix[i - 1][j] - '0' : 0; 25 | int corner = i > 0 && j > 0 ? matrix[i - 1][j - 1] - '0' : 0; 26 | matrix[i][j] = (char) (Math.min(Math.min(left, top), corner) + 1 + '0'); 27 | result = Math.max(matrix[i][j] - '0', result); 28 | } 29 | } 30 | } 31 | return result * result; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Permutations/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/permutations 2 | // 3 | // 4 | // Given a collection of distinct numbers, return all possible permutations. 5 | // 6 | // 7 | // For example, 8 | // [1,2,3] have the following permutations: 9 | // 10 | // [ 11 | // [1,2,3], 12 | // [1,3,2], 13 | // [2,1,3], 14 | // [2,3,1], 15 | // [3,1,2], 16 | // [3,2,1] 17 | // ] 18 | // 19 | // 20 | public class Solution { 21 | 22 | int[] nums; 23 | List> result = new ArrayList<>(); 24 | 25 | private void swap(int l, int r) { 26 | int t = nums[l]; 27 | nums[l] = nums[r]; 28 | nums[r] = t; 29 | } 30 | 31 | public List> permute(int[] nums) { 32 | this.nums = nums; 33 | permute(0, nums.length - 1); 34 | return result; 35 | } 36 | 37 | private void permute(int left, int right) { 38 | if (left == right) { 39 | List temp = new ArrayList<>(); 40 | for (int i : nums) temp.add(i); 41 | result.add(temp); 42 | } 43 | else { 44 | for (int i = left; i <= right; i++) { 45 | swap(left, i); 46 | permute(left + 1, right); 47 | swap(i, left); 48 | } 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /Search for a Range/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/search-for-a-range 2 | // 3 | // Given an array of integers sorted in ascending order, find the starting and ending position of a given target value. 4 | // Your algorithm's runtime complexity must be in the order of O(log n). 5 | // If the target is not found in the array, return [-1, -1]. 6 | // 7 | // For example, 8 | // Given [5, 7, 7, 8, 8, 10] and target value 8, 9 | // return [3, 4]. 10 | // 11 | public class Solution { 12 | public int[] searchRange(int[] nums, int target) { 13 | int left = 0; 14 | int right = nums.length - 1; 15 | int[] result = {-1, -1}; 16 | if(nums.length == 0) return result; 17 | 18 | while (left < right) { 19 | int mid = (left + right) /2; 20 | if (nums[mid] < target) left = mid + 1; 21 | else right = mid; 22 | } 23 | 24 | if (nums[left] != target) return result; 25 | else result[0] = left; 26 | 27 | right = nums.length - 1; 28 | 29 | while (left < right) { 30 | int mid = (left + right) /2 + 1; 31 | if (nums[mid] > target) right = mid - 1; 32 | else left = mid; 33 | } 34 | result[1] = right; 35 | return result; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /Fizz Buzz/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/fizz-buzz 2 | // 3 | // Write a program that outputs the string representation of numbers from 1 to n. 4 | // But for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”. For numbers which are multiples of both three and five output “FizzBuzz”. 5 | // Example: 6 | // 7 | // n = 15, 8 | // 9 | // Return: 10 | // [ 11 | // "1", 12 | // "2", 13 | // "Fizz", 14 | // "4", 15 | // "Buzz", 16 | // "Fizz", 17 | // "7", 18 | // "8", 19 | // "Fizz", 20 | // "Buzz", 21 | // "11", 22 | // "Fizz", 23 | // "13", 24 | // "14", 25 | // "FizzBuzz" 26 | // ] 27 | // 28 | // 29 | public class Solution { 30 | public List fizzBuzz(int n) { 31 | List array = new ArrayList<>(); 32 | for (int i = 1; i <= n; i++) { 33 | if (i % 3 == 0 && i % 5 == 0) { 34 | array.add("FizzBuzz"); 35 | } 36 | else if (i % 3 == 0) { 37 | array.add("Fizz"); 38 | } 39 | else if (i % 5 == 0) { 40 | array.add("Buzz"); 41 | } else { 42 | array.add(Integer.toString(i)); 43 | } 44 | } 45 | return array; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /Convert Sorted List to Binary Search Tree/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree 2 | // 3 | // Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST. 4 | /** 5 | * Definition for singly-linked list. 6 | * public class ListNode { 7 | * int val; 8 | * ListNode next; 9 | * ListNode(int x) { val = x; } 10 | * } 11 | */ 12 | /** 13 | * Definition for a binary tree node. 14 | * public class TreeNode { 15 | * int val; 16 | * TreeNode left; 17 | * TreeNode right; 18 | * TreeNode(int x) { val = x; } 19 | * } 20 | */ 21 | public class Solution { 22 | public TreeNode sortedListToBST(ListNode head) { 23 | if (head == null) return null; 24 | ListNode slow = head; 25 | if (head.next == null) return new TreeNode(slow.val); 26 | ListNode fast = head.next.next; 27 | while (fast != null && fast.next != null) { 28 | slow = slow.next; 29 | fast = fast.next.next; 30 | } 31 | ListNode newHead = slow.next; 32 | slow.next = null; 33 | TreeNode root = new TreeNode(newHead.val); 34 | root.left = sortedListToBST(head); 35 | root.right = sortedListToBST(newHead.next); 36 | return root; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Triangle/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/triangle 2 | // 3 | // Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below. 4 | // 5 | // For example, given the following triangle 6 | // [ 7 | // [2], 8 | // [3,4], 9 | // [6,5,7], 10 | // [4,1,8,3] 11 | // ] 12 | // 13 | // The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11). 14 | // 15 | // Note: 16 | // Bonus point if you are able to do this using only O(n) extra space, where n is the total number of rows in the triangle. 17 | public class Solution { 18 | public int minimumTotal(List> triangle) { 19 | for (int i = 1; i < triangle.size(); i++) { 20 | triangle.get(i).set(0, triangle.get(i).get(0) + triangle.get(i - 1).get(0)); // set left border 21 | triangle.get(i).set(triangle.get(i).size() - 1, triangle.get(i).get(triangle.get(i).size() - 1) + triangle.get(i - 1).get(triangle.get(i - 1).size() - 1)); // set right border 22 | for (int j = 1; j < triangle.get(i).size() - 1; j++) triangle.get(i).set(j, Math.min(triangle.get(i - 1).get(j - 1) + triangle.get(i).get(j), triangle.get(i - 1).get(j) + triangle.get(i).get(j))); 23 | } 24 | return Collections.min(triangle.get(triangle.size() - 1)); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Self Dividing Numbers/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/self-dividing-numbers/ 2 | // 3 | // A self-dividing number is a number that is divisible by every digit it contains. 4 | // 5 | // For example, 128 is a self-dividing number because 128 % 1 == 0, 128 % 2 == 0, and 128 % 8 == 0. 6 | // 7 | // Also, a self-dividing number is not allowed to contain the digit zero. 8 | // 9 | // Given a lower and upper number bound, output a list of every possible self dividing number, including the bounds if possible. 10 | // 11 | // Example 1: 12 | // Input: 13 | // left = 1, right = 22 14 | // Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 15, 22] 15 | // Note: 16 | // 17 | // The boundaries of each input argument are 1 <= left <= right <= 10000. 18 | class Solution { 19 | public List selfDividingNumbers(int left, int right) { 20 | List result = new ArrayList<>(); 21 | for (int i = left; i <= right; i++) { 22 | if (isSelfDividing(i)) { 23 | result.add(i); 24 | } 25 | } 26 | return result; 27 | } 28 | 29 | private boolean isSelfDividing(int i) { 30 | int base = i; 31 | while (i > 0) { 32 | if (i % 10 == 0 || base % (i % 10) != 0) return false; 33 | i /= 10; 34 | } 35 | return true; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /First Bad Version/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/first-bad-version 2 | // 3 | // 4 | // You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad. 5 | // 6 | // 7 | // Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following ones to be bad. 8 | // 9 | // 10 | // You are given an API bool isBadVersion(version) which will return whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API. 11 | // 12 | // Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases. 13 | /* The isBadVersion API is defined in the parent class VersionControl. 14 | boolean isBadVersion(int version); */ 15 | 16 | public class Solution extends VersionControl { 17 | public int firstBadVersion(int n) { 18 | int left = 1; 19 | int right = n; 20 | while(left < right) { 21 | int mid = left + (right - left) / 2; 22 | if (!isBadVersion(mid)) left = mid + 1; 23 | else right = mid; 24 | } 25 | return left; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Minimum Size Subarray Sum/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/minimum-size-subarray-sum 2 | // 3 | // 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. 4 | // 5 | // For example, given the array [2,3,1,2,4,3] and s = 7, 6 | // the subarray [4,3] has the minimal length under the problem constraint. 7 | // 8 | // click to show more practice. 9 | // 10 | // More practice: 11 | // If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n). 12 | // 13 | // Credits: 14 | // Special thanks to @Freezen for adding this problem and creating all test cases. 15 | class Solution { 16 | public int minSubArrayLen(int s, int[] nums) { 17 | int result = Integer.MAX_VALUE; 18 | int sum = 0; 19 | int first = 0; 20 | int second = 0; 21 | while (second <= nums.length) { 22 | while (sum >= s) { 23 | result = Math.min(result, second - first); 24 | sum -= nums[first]; 25 | first++; 26 | } 27 | if (second == nums.length) break; 28 | sum += nums[second]; 29 | second++; 30 | } 31 | return result == Integer.MAX_VALUE ? 0 : result; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Number of Boomerangs/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/number-of-boomerangs 2 | // 3 | // Given n points in the plane that are all pairwise distinct, a "boomerang" is a tuple of points (i, j, k) such that the distance between i and j equals the distance between i and k (the order of the tuple matters). 4 | // 5 | // Find the number of boomerangs. You may assume that n will be at most 500 and coordinates of points are all in the range [-10000, 10000] (inclusive). 6 | // 7 | // Example: 8 | // Input: 9 | // [[0,0],[1,0],[2,0]] 10 | // 11 | // Output: 12 | // 2 13 | // 14 | // Explanation: 15 | // The two boomerangs are [[1,0],[0,0],[2,0]] and [[1,0],[2,0],[0,0]] 16 | class Solution { 17 | public int numberOfBoomerangs(int[][] points) { 18 | int result = 0; 19 | for (int[] first: points) { 20 | Map map = new HashMap<>(); 21 | for (int[] second : points) { 22 | long distance = getDistance(first, second); 23 | int t = map.getOrDefault(distance, 0); 24 | result += t * 2; 25 | map.put(distance, t + 1); 26 | } 27 | } 28 | return result; 29 | } 30 | 31 | private long getDistance(int[] p1, int[] p2) { 32 | return (p2[0] - p1[0]) * (p2[0] - p1[0]) + (p2[1] - p1[1]) * (p2[1] - p1[1]); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Daily Temperatures/Solution_O_m+n.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/daily-temperatures 2 | // 3 | // 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. 4 | // 5 | // 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]. 6 | // 7 | // Note: The length of temperatures will be in the range [1, 30000]. Each temperature will be an integer in the range [30, 100]. 8 | class Solution { 9 | public int[] dailyTemperatures(int[] temperatures) { 10 | int length = temperatures.length; 11 | int[] result = new int[length]; 12 | int[] temp = new int[101]; 13 | result[length - 1] = 0; 14 | temp[temperatures[length - 1]] = length - 1; 15 | for (int i = length - 2; i >= 0; i--) { 16 | int distance = length; 17 | for (int j = temperatures[i] + 1; j <= 100; j++) { 18 | if (temp[j] != 0) { 19 | distance = Math.min(distance, temp[j] - i); 20 | } 21 | } 22 | result[i] = distance == length ? 0 : distance; 23 | temp[temperatures[i]] = i; 24 | } 25 | return result; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Happy Number/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/happy-number 2 | // 3 | // Write an algorithm to determine if a number is "happy". 4 | // A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers. 5 | // Example: 19 is a happy number 6 | // 7 | // 12 + 92 = 82 8 | // 82 + 22 = 68 9 | // 62 + 82 = 100 10 | // 12 + 02 + 02 = 1 11 | // 12 | // Credits:Special thanks to @mithmatt and @ts for adding this problem and creating all test cases. 13 | public class Solution { 14 | public boolean isHappy(int n) { 15 | Set set = new HashSet<>(); 16 | int temp = n; 17 | while (calculate(n) != temp && n != 1) { 18 | if (!set.add(n)) { 19 | return false; 20 | } else { 21 | n = calculate(n); 22 | } 23 | 24 | } 25 | return n == 1; 26 | } 27 | 28 | static int calculate(int n) { 29 | int result = 0; 30 | do { 31 | result += (n % 10) * (n % 10); 32 | n /= 10; 33 | } while (n > 0); 34 | return result; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Rotate List/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/rotate-list 2 | // 3 | // Given a list, rotate the list to the right by k places, where k is non-negative. 4 | // For example: 5 | // Given 1->2->3->4->5->NULL and k = 2, 6 | // return 4->5->1->2->3->NULL. 7 | public class Solution { 8 | public ListNode rotateRight(ListNode head, int k) { 9 | if (head == null || k == 0) return head; 10 | if (head.next == null) return head; 11 | int len = 0; 12 | ListNode l = head; 13 | while (l != null) { 14 | l = l.next; 15 | len++; 16 | } 17 | if (k == len) { 18 | return head; 19 | } 20 | k %= len; 21 | if (k == 0) { 22 | return head; 23 | } 24 | ListNode slow = head; 25 | ListNode fast = head.next; 26 | while (fast != null) { 27 | fast = fast.next; 28 | if (--k <= 0) { 29 | slow = slow.next; 30 | } 31 | } 32 | ListNode current = head; 33 | while (current.next != slow) { 34 | current = current.next; 35 | } 36 | current.next = null; 37 | ListNode temp = slow; 38 | while (temp.next != null) { 39 | temp = temp.next; 40 | } 41 | temp.next = head; 42 | return slow; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /Reaching Points/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/reaching-points 2 | // 3 | // A move consists of taking a point (x, y) and transforming it to either (x, x+y) or (x+y, y). 4 | // 5 | // Given a starting point (sx, sy) and a target point (tx, ty), return True if and only if a sequence of moves exists to transform the point (sx, sy) to (tx, ty). Otherwise, return False. 6 | // 7 | // Examples: 8 | // Input: sx = 1, sy = 1, tx = 3, ty = 5 9 | // Output: True 10 | // Explanation: 11 | // One series of moves that transforms the starting point to the target is: 12 | // (1, 1) -> (1, 2) 13 | // (1, 2) -> (3, 2) 14 | // (3, 2) -> (3, 5) 15 | // 16 | // Input: sx = 1, sy = 1, tx = 2, ty = 2 17 | // Output: False 18 | // 19 | // Input: sx = 1, sy = 1, tx = 1, ty = 1 20 | // Output: True 21 | // 22 | // Note: 23 | // 24 | // sx, sy, tx, ty will all be integers in the range [1, 10^9]. 25 | class Solution { 26 | public boolean reachingPoints(int sx, int sy, int tx, int ty) { 27 | while (sx < tx && sy < ty) { 28 | if (tx > ty) { 29 | tx %= ty; 30 | } else { 31 | ty %= tx; 32 | } 33 | } 34 | if (sx == tx) { 35 | return (ty - sy) % sx == 0; 36 | } else { 37 | if (sy == ty) return (tx - sx) % sy == 0; 38 | } 39 | return false; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /Longest Palindromic Subsequence/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/longest-palindromic-subsequence 2 | // 3 | // 4 | // Given a string s, find the longest palindromic subsequence's length in s. You may assume that the maximum length of s is 1000. 5 | // 6 | // Example 1: 7 | // Input: 8 | // 9 | // "bbbab" 10 | // 11 | // Output: 12 | // 13 | // 4 14 | // 15 | // One possible longest palindromic subsequence is "bbbb". 16 | // 17 | // Example 2: 18 | // Input: 19 | // 20 | // "cbbd" 21 | // 22 | // Output: 23 | // 24 | // 2 25 | // 26 | // One possible longest palindromic subsequence is "bb". 27 | // 28 | public class Solution { 29 | public int longestPalindromeSubseq(String s) { 30 | char[] array = s.toCharArray(); 31 | int length = array.length; 32 | if (length == 0) return 0; 33 | int[][] dp = new int[length][length]; 34 | int temp = 0; 35 | for (int i = length - 1; i >= 0; i--) { 36 | dp[i][i] = 1; 37 | for (int j = i + 1; j < length; j++) { 38 | if (array[i] == array[j]) { 39 | temp = dp[i + 1][j - 1] + 2; 40 | } else { 41 | temp = Math.max(dp[i + 1][j], dp[i][j - 1]); 42 | } 43 | dp[i][j] = temp; 44 | } 45 | } 46 | return dp[0][length - 1]; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /Minimum Absolute Difference in BST/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/minimum-absolute-difference-in-bst 2 | // 3 | // Given a binary search tree with non-negative values, find the minimum absolute difference between values of any two nodes. 4 | // 5 | // Example: 6 | // 7 | // Input: 8 | // 9 | // 1 10 | // \ 11 | // 3 12 | // / 13 | // 2 14 | // 15 | // Output: 16 | // 1 17 | // 18 | // Explanation: 19 | // The minimum absolute difference is 1, which is the difference between 2 and 1 (or between 2 and 3). 20 | // 21 | // 22 | // Note: 23 | // There are at least two nodes in this BST. 24 | // 25 | /** 26 | * Definition for a binary tree node. 27 | * public class TreeNode { 28 | * int val; 29 | * TreeNode left; 30 | * TreeNode right; 31 | * TreeNode(int x) { val = x; } 32 | * } 33 | */ 34 | public class Solution { 35 | 36 | Integer min = Integer.MAX_VALUE; 37 | Integer helper; 38 | 39 | public int getMinimumDifference(TreeNode root) { 40 | if (root == null) return 0; 41 | find(root); 42 | return min; 43 | } 44 | 45 | private void find(TreeNode root) { 46 | if (root == null) return; 47 | find(root.left); 48 | if (helper != null) min = Math.min(Math.abs(root.val - helper), min); 49 | helper = root.val; 50 | find(root.right); 51 | } 52 | 53 | } 54 | -------------------------------------------------------------------------------- /One Edit Distance/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/one-edit-distance 2 | // 3 | // Given two strings S and T, determine if they are both one edit distance apart. 4 | class Solution { 5 | public boolean isOneEditDistance(String s, String t) { 6 | if (s == null && t == null) return false; 7 | if (s == null || t == null) return false; 8 | if (s.equals(t)) return false; 9 | if (s.length() == t.length()) return isSameAfterChangeOneLetter(s, t); 10 | return isSameAfterDeleteOneChar(s, t); 11 | } 12 | 13 | private boolean isSameAfterDeleteOneChar(String s, String t) { 14 | if (Math.abs(s.length() - t.length()) > 1) return false; 15 | for (int i = 0; i < s.length() && i < t.length(); i++) { 16 | if (s.charAt(i) != t.charAt(i)) { 17 | return s.substring(i).equals(t.substring(i + 1)) || s.substring(i + 1).equals(t.substring(i)); 18 | } 19 | } 20 | return true; 21 | } 22 | 23 | private boolean isSameAfterChangeOneLetter(String s, String t) { 24 | boolean foundOneLetter = false; 25 | for (int i = 0; i < s.length(); i++) { 26 | if (s.charAt(i) != t.charAt(i)) { 27 | if (foundOneLetter) return false; 28 | foundOneLetter = true; 29 | } 30 | } 31 | return foundOneLetter; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Letter Combinations of a Phone Number/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/letter-combinations-of-a-phone-number 2 | // 3 | // Given a digit string, return all possible letter combinations that the number could represent. 4 | // 5 | // 6 | // A mapping of digit to letters (just like on the telephone buttons) is given below. 7 | // 8 | // 9 | // Input:Digit string "23" 10 | // Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]. 11 | // 12 | // 13 | // Note: 14 | // Although the above answer is in lexicographical order, your answer could be in any order you want. 15 | // 16 | public class Solution { 17 | public List letterCombinations(String digits) { 18 | String[] values = new String[]{"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; 19 | List result = new ArrayList<>(); 20 | if (digits.length() > 0) result.add(""); 21 | for (int i = 0; i < digits.length(); i++) { 22 | String string= values[(int) digits.charAt(i) - '0']; 23 | List temp = new ArrayList<>(result); 24 | result.clear(); 25 | for (int k = 0; k < string.length(); k++) { 26 | for (String t : temp) { 27 | t += string.charAt(k); 28 | result.add(t); 29 | } 30 | } 31 | } 32 | return result; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Spiral Matrix II/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/spiral-matrix-ii 2 | // 3 | // Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. 4 | // 5 | // For example, 6 | // Given n = 3, 7 | // 8 | // You should return the following matrix: 9 | // 10 | // [ 11 | // [ 1, 2, 3 ], 12 | // [ 8, 9, 4 ], 13 | // [ 7, 6, 5 ] 14 | // ] 15 | // 16 | public class Solution { 17 | public int[][] generateMatrix(int n) { 18 | int matrix[][] = new int[n][n]; 19 | if (n == 0) return matrix; 20 | int u = 0, d = n - 1, l = 0, r = n - 1; 21 | int f = 1; 22 | while (f <= n * n) { 23 | // up 24 | for (int col = l; col <= r; col++){ 25 | matrix[u][col] = f++; 26 | } 27 | if (++u > d) break; 28 | // right 29 | for (int row = u; row <= d; row++){ 30 | matrix[row][r] = f++; 31 | } 32 | if (--r < l) break; 33 | // down 34 | for (int col = r; col >= l; col--){ 35 | matrix[d][col] = f++; 36 | } 37 | if (--d < u) break; 38 | // left 39 | for (int row = d; row >= u; row--){ 40 | matrix[row][l] = f++; 41 | } 42 | if (++l > r) break; 43 | } 44 | return matrix; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /Trapping Rain Water/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/trapping-rain-water 2 | // 3 | // 4 | // 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. 5 | // 6 | // 7 | // For example, 8 | // Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6. 9 | // 10 | // 11 | // 12 | // The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image! 13 | class Solution { 14 | public int trap(int[] height) { 15 | int result = 0; 16 | int left = 0; 17 | int right = height.length - 1; 18 | int leftMax = 0; 19 | int rightMax = 0; 20 | while (left < right) { 21 | // Define tempLeft and tempRight to reduce accesses to array 22 | int tempLeft = height[left]; 23 | int tempRight = height[right]; 24 | if (tempLeft < tempRight) { 25 | leftMax = Math.max(leftMax, tempLeft); 26 | result += leftMax - tempLeft; 27 | left++; 28 | } else { 29 | rightMax = Math.max(rightMax, tempRight); 30 | result += rightMax - tempRight; 31 | right--; 32 | } 33 | } 34 | return result; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /3Sum Closest/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/3sum-closest 2 | // 3 | // Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution. 4 | // 5 | // For example, given array S = {-1 2 1 -4}, and target = 1. 6 | // 7 | // The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). 8 | class Solution { 9 | public int threeSumClosest(int[] nums, int target) { 10 | Arrays.sort(nums); 11 | int result = nums[0] + nums[1] + nums[2]; 12 | int length = nums.length; 13 | for (int i = 0; i < length - 2; i++) { 14 | int temp = -nums[i]; 15 | int left = i + 1; 16 | int right = length - 1; 17 | while (left < right) { 18 | int sum = nums[left] + nums[right] + nums[i]; 19 | if (Math.abs(target - result) > Math.abs(target - sum)) { 20 | result = sum; 21 | if (result == target) { 22 | return result; 23 | } 24 | } 25 | if (sum > target) { 26 | right--; 27 | } else { 28 | left++; 29 | } 30 | } 31 | } 32 | return result; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Majority Element II/Solution.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/majority-element-ii 2 | // 3 | // Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. The algorithm should run in linear time and in O(1) space. 4 | public class Solution { 5 | public List majorityElement(int[] nums) { 6 | List result = new ArrayList<>(); 7 | int first = 0; 8 | int second = 1; 9 | int firstCount = 0; 10 | int secondCount = 0; 11 | for (int i : nums) { 12 | if (first == i) { 13 | firstCount++; 14 | } else if (second == i) { 15 | secondCount++; 16 | } else if (firstCount == 0) { 17 | first = i; 18 | firstCount++; 19 | } else if (secondCount == 0) { 20 | second = i; 21 | secondCount++; 22 | } else { 23 | firstCount--; 24 | secondCount--; 25 | } 26 | } 27 | firstCount = 0; 28 | secondCount = 0; 29 | for (int i : nums) { 30 | if (i == first) firstCount++; 31 | if (i == second) secondCount++; 32 | } 33 | if (firstCount * 3 > nums.length) result.add(first); 34 | if (secondCount * 3 > nums.length) result.add(second); 35 | return result; 36 | } 37 | } 38 | --------------------------------------------------------------------------------