└── problems └── src ├── math ├── AddDigits.java ├── CountPrimes.java ├── ExcelSheetColumnTitle.java ├── RomanToInteger.java ├── WaterAndJugProblem.java ├── BulbSwitcherII.java ├── GlobalAndLocalInversions.java └── RotateFunction.java ├── binary_search ├── SqrtX.java ├── PowXN.java ├── SearchInsertPosition.java ├── HIndexII.java ├── MinSortedRotatedArray.java ├── FirstBadVersion.java └── SearchRotatedSortedArray.java ├── dynamic_programming ├── ClimbingStairs.java ├── MaximumSubarray.java ├── UniqueBinarySearchTrees.java ├── MaximumProductSubarray.java ├── HouseRobber.java ├── LongestPalindromicSubsequence.java ├── LongestIncreasingSubsequence.java ├── DecodeWays.java ├── TwoKeysKeyboard.java ├── BestTimeToBuyAndSellStocks.java ├── CombinationSumIV.java ├── MaximalSquare.java ├── LongestPaliandromicSubstring.java ├── BestTimeToBuyAndSellStockIII.java ├── SplitArrayLargestSum.java ├── BestTimeToBuyAndSellStocksWithFee.java ├── CoinChange2.java ├── PalindromicSubstrings.java └── ContinuousSubarraySum.java ├── array ├── MissingNumber.java ├── MergeSortedArray.java ├── MaxProductOfThreeNumbers.java ├── ProductOfArrayExceptSelf.java ├── RotateArray.java ├── FirstMissingPositive.java ├── ReadNCharacters.java ├── PascalsTriangle.java ├── IncreasingTripletSubsequence.java ├── MeetingRooms.java ├── RotateMatrix.java ├── TwoSumII.java ├── LongestIncreasingSubsequence.java ├── LargestNumberAtLeastTwice.java ├── SetMatrixZeroes.java ├── MaximumSwap.java ├── ThirdMaximumNumber.java ├── CanPlaceFlowers.java ├── SubarraySumEqualsK.java └── ImageSmoother.java ├── string ├── ExcelSheetColumnNumber.java ├── FirstUniqueCharacterInAString.java ├── ImplementStrStr.java ├── ValidPalindromeII.java ├── ValidPalindrome.java ├── AddBinary.java ├── OneEditDistance.java ├── CountAndSay.java ├── RepeatedSubstringPattern.java ├── ReverseWordsInAString.java ├── SimplifyPath.java ├── PermutationInString.java └── StringToInteger.java ├── tree ├── ConvertSortedArrayToBST.java ├── SumofLeftLeaves.java ├── BinaryTreePaths.java ├── MinimumAbsoluteDifferenceInBST.java ├── SymmetricTree.java ├── TwoSumIV.java ├── DiameterOfBinaryTree.java ├── SortedArrayToBST.java ├── SameTree.java ├── LowestCommonAncestorBST.java ├── PreorderToBT.java ├── LCA.java ├── BSTtoDoublyLinkedList.java ├── FindBottomLeftTreeValue.java ├── ZigZagTraversal.java ├── SubtreeOfAnotherTree.java ├── BinaryTreeInorderTraversal.java ├── ClosestBinarySearchTreeValue.java ├── BinarayTreeRightSideView.java └── BinaryTreeMaximumPathSum.java ├── greedy ├── JumpGame.java ├── JumpGameII.java ├── QueueReconstructionByHeight.java ├── GasStation.java └── BurstBalloons.java ├── bit_manipulation ├── HammingDistance.java ├── GrayCode.java ├── DivideTwoIntegers.java └── TotalHammingDistance.java ├── two_pointers ├── RemoveDuplicates.java ├── MoveZeroes.java ├── RemoveDuplicatesII.java ├── TrappingRainWater.java ├── LongestSubstringWitoutRepeats.java ├── MinimumSizeSubarraySum.java ├── ThreeSum.java └── ThreeSumClosest.java ├── backtracking ├── GenerateParentheses.java ├── Subsets.java ├── Combinations.java ├── PermutationsII.java ├── Permutations.java ├── SubsetsII.java ├── TargetSum.java ├── PalindromePartitioning.java ├── LetterPhoneNumber.java ├── CombinationSumII.java └── CombinationSum.java ├── hashing ├── ValidAnagram.java ├── ContiguousArray.java ├── TwoSum.java └── MaximumSizeSubarraySumEqualsk.java ├── linked_list ├── DeleteNode.java ├── LinkedListCycle.java ├── ReverseLinkedList.java ├── MergeTwoSortedList.java └── SwapNodesInPairs.java ├── design └── EncodeAndDecodeTinyURL.java ├── stack ├── ValidParentheses.java └── MinStack.java ├── divide_and_conquer ├── KthLargestElementInAnArray.java └── SearchA2DMatrix.java ├── depth_first_search ├── MovieRecommend.java └── NumberOfIslands.java └── reservoir_sampling └── RandomPickIndex.java /problems/src/math/AddDigits.java: -------------------------------------------------------------------------------- 1 | package math; 2 | 3 | /** 4 | * Created by gouthamvidyapradhan on 02/08/2017. 5 | * Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. 6 | *
7 | * For example: 8 | *
9 | * Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it. 10 | *
11 | * Follow up: 12 | * Could you do it without any loop/recursion in O(1) runtime? 13 | */ 14 | public class AddDigits { 15 | 16 | public static void main(String[] args) throws Exception { 17 | System.out.println(new AddDigits().addDigits(38)); 18 | } 19 | 20 | public int addDigits(int num) { 21 | if (num == 0) return 0; 22 | return num % 9 == 0 ? 9 : num % 9; 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /problems/src/binary_search/SqrtX.java: -------------------------------------------------------------------------------- 1 | package binary_search; 2 | 3 | /** 4 | * Created by gouthamvidyapradhan on 22/05/2017. 5 | * Implement int sqrt(int x). 6 | *
7 | * Compute and return the square root of x. 8 | */ 9 | public class SqrtX { 10 | public static void main(String[] args) throws Exception { 11 | System.out.println(new SqrtX().mySqrt(Integer.MAX_VALUE)); 12 | } 13 | 14 | public int mySqrt(int x) { 15 | int s = 0, e = x; 16 | long ans = 0L; 17 | while (s <= e) { 18 | long m = s + (e - s) / 2; 19 | long prod = m * m; 20 | if (prod <= x) { 21 | s = (int) (m + 1); 22 | ans = m; 23 | } else e = (int) m - 1; 24 | } 25 | return (int) ans; 26 | } 27 | 28 | 29 | } 30 | -------------------------------------------------------------------------------- /problems/src/binary_search/PowXN.java: -------------------------------------------------------------------------------- 1 | package binary_search; 2 | 3 | /** 4 | * Created by gouthamvidyapradhan on 23/05/2017. 5 | *
6 | * Implement pow(x, n). 7 | *
8 | * Solution: Works with O(log n) 9 | */ 10 | public class PowXN { 11 | /** 12 | * Main method 13 | * 14 | * @param args 15 | * @throws Exception 16 | */ 17 | public static void main(String[] args) throws Exception { 18 | System.out.println(1 / new PowXN().myPow(2.00000, -2147483648)); 19 | } 20 | 21 | public double myPow(double x, int n) { 22 | if (n == 0) return 1D; 23 | long N = n; //use long to avoid overflow. 24 | return solve(n < 0 ? (1 / x) : x, N < 0 ? (N * -1) : N); 25 | } 26 | 27 | public double solve(double x, long n) { 28 | if (n == 1) return x; 29 | double val = solve(x, n / 2); 30 | return val * val * ((n % 2) == 0 ? 1 : x); 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /problems/src/dynamic_programming/ClimbingStairs.java: -------------------------------------------------------------------------------- 1 | package dynamic_programming; 2 | 3 | /** 4 | * Created by gouthamvidyapradhan on 01/04/2017. 5 | * You are climbing a stair case. It takes n steps to reach to the top. 6 | *
7 | * Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? 8 | *
9 | * Note: Given n will be a positive integer. 10 | */ 11 | public class ClimbingStairs { 12 | /** 13 | * Main method 14 | * 15 | * @param args 16 | * @throws Exception 17 | */ 18 | public static void main(String[] args) throws Exception { 19 | 20 | } 21 | 22 | public int climbStairs(int n) { 23 | if (n == 0 || n == 1) return 1; 24 | int[] A = new int[n + 1]; 25 | A[n] = 1; 26 | A[n - 1] = 1; 27 | for (int i = n - 2; i >= 0; i--) 28 | A[i] = A[i + 1] + A[i + 2]; 29 | return A[0]; 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /problems/src/array/MissingNumber.java: -------------------------------------------------------------------------------- 1 | package array; 2 | 3 | /** 4 | * Created by gouthamvidyapradhan on 04/07/2017. 5 | * Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array. 6 | *
7 | * For example, 8 | * Given nums = [0, 1, 3] return 2. 9 | *
10 | * Note: 11 | * Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity? 12 | */ 13 | public class MissingNumber { 14 | 15 | public static void main(String[] args) throws Exception { 16 | int[] nums = {0}; 17 | System.out.println(new MissingNumber().missingNumber(nums)); 18 | } 19 | 20 | public int missingNumber(int[] nums) { 21 | int sum = 0; 22 | int n = nums.length; 23 | for (int num : nums) { 24 | sum += num; 25 | } 26 | int arrSum = (((n + 1)) * n) / 2; 27 | if (arrSum == sum) return 0; 28 | else return arrSum - sum; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /problems/src/dynamic_programming/MaximumSubarray.java: -------------------------------------------------------------------------------- 1 | package dynamic_programming; 2 | 3 | /** 4 | * Created by gouthamvidyapradhan on 07/07/2017. 5 | * Find the contiguous subarray within an array (containing at least one number) which has the largest sum. 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 | public class MaximumSubarray { 11 | public static void main(String[] args) throws Exception { 12 | int[] nums = {-2, 1, -3, 4, -1, 2, 1, -5, 4}; 13 | System.out.println(new MaximumSubarray().maxSubArray(nums)); 14 | } 15 | 16 | public int maxSubArray(int[] nums) { 17 | if (nums.length == 1) return nums[0]; 18 | int max = nums[nums.length - 1]; 19 | for (int i = nums.length - 2; i >= 0; i--) { 20 | nums[i] = Math.max(nums[i], nums[i] + nums[i + 1]); 21 | max = Math.max(max, nums[i]); 22 | } 23 | return max; 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /problems/src/string/ExcelSheetColumnNumber.java: -------------------------------------------------------------------------------- 1 | package string; 2 | 3 | /** 4 | * Created by gouthamvidyapradhan on 07/07/2017. 5 | * Given a column title as appear in an Excel sheet, return its corresponding column number. 6 | *
7 | * For example: 8 | *
9 | * A -> 1 10 | * B -> 2 11 | * C -> 3 12 | * ... 13 | * Z -> 26 14 | * AA -> 27 15 | * AB -> 28 16 | */ 17 | public class ExcelSheetColumnNumber { 18 | String CONST = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; 19 | 20 | public static void main(String[] args) throws Exception { 21 | System.out.println(new ExcelSheetColumnNumber().titleToNumber("AAB")); 22 | } 23 | 24 | public int titleToNumber(String s) { 25 | int total = 0; 26 | int j = 0; 27 | for (int i = s.length() - 1; i >= 0; i--) { 28 | char c = s.charAt(i); 29 | int pos = CONST.indexOf(c) + 1; 30 | int pow = (int) Math.pow(26, j++); 31 | total += (pow * pos); 32 | } 33 | return total; 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /problems/src/array/MergeSortedArray.java: -------------------------------------------------------------------------------- 1 | package array; 2 | 3 | /** 4 | * Created by gouthamvidyapradhan on 29/07/2017. 5 | * Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. 6 | *
7 | * Note: 8 | * You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. The number of elements initialized in nums1 and nums2 are m and n respectively. 9 | */ 10 | public class MergeSortedArray { 11 | public static void main(String[] args) throws Exception { 12 | int[] A = {0}; 13 | int[] B = {1}; 14 | new MergeSortedArray().merge(A, 0, B, 1); 15 | for (int i : A) 16 | System.out.println(i); 17 | } 18 | 19 | public void merge(int[] nums1, int m, int[] nums2, int n) { 20 | int i = m + n - 1, j = m - 1, k = n - 1; 21 | while (j >= 0 && k >= 0) 22 | nums1[i--] = (nums1[j] > nums2[k]) ? nums1[j--] : nums2[k--]; 23 | while (k >= 0) 24 | nums1[i--] = nums2[k--]; 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /problems/src/tree/ConvertSortedArrayToBST.java: -------------------------------------------------------------------------------- 1 | package tree; 2 | 3 | /** 4 | * Created by gouthamvidyapradhan on 09/03/2017. 5 | * Given an array where elements are sorted in ascending order, convert it to a height balanced BST. 6 | */ 7 | public class ConvertSortedArrayToBST { 8 | public class TreeNode { 9 | int val; 10 | TreeNode left; 11 | TreeNode right; 12 | 13 | TreeNode(int x) { 14 | val = x; 15 | } 16 | } 17 | 18 | public TreeNode sortedArrayToBST(int[] nums) { 19 | if (nums.length == 0) return null; 20 | return build(0, nums.length - 1, nums); 21 | } 22 | 23 | private TreeNode build(int s, int e, int[] nums) { 24 | if (s > e) return null; 25 | 26 | int m = (e - s) / 2; 27 | int node = nums[s + m]; 28 | TreeNode root = new TreeNode(node); 29 | if (s == e) 30 | return root; 31 | 32 | root.left = build(s, s + m - 1, nums); 33 | root.right = build(s + m + 1, e, nums); 34 | 35 | return root; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /problems/src/binary_search/SearchInsertPosition.java: -------------------------------------------------------------------------------- 1 | package binary_search; 2 | 3 | /** 4 | * Created by gouthamvidyapradhan on 22/05/2017. 5 | * 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. 6 | *
7 | * You may assume no duplicates in the array. 8 | *
9 | * Here are few examples. 10 | * [1,3,5,6], 5 → 2 11 | * [1,3,5,6], 2 → 1 12 | * [1,3,5,6], 7 → 4 13 | * [1,3,5,6], 0 → 0 14 | */ 15 | public class SearchInsertPosition { 16 | public static void main(String[] args) throws Exception { 17 | int[] A = {1, 3, 5, 6}; 18 | new SearchInsertPosition().searchInsert(A, 5); 19 | } 20 | 21 | public int searchInsert(int[] nums, int target) { 22 | int pos = nums.length; 23 | int s = 0, e = nums.length - 1; 24 | while (s <= e) { 25 | int m = s + (e - s) / 2; 26 | if (nums[m] >= target) { 27 | pos = m; 28 | e = m - 1; 29 | } else s = m + 1; 30 | } 31 | return pos; 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /problems/src/array/MaxProductOfThreeNumbers.java: -------------------------------------------------------------------------------- 1 | package array; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | * Created by gouthamvidyapradhan on 27/06/2017. 7 | * Given an integer array, find three numbers whose product is maximum and output the maximum product. 8 | *
9 | * Example 1: 10 | * Input: [1,2,3] 11 | * Output: 6 12 | * Example 2: 13 | * Input: [1,2,3,4] 14 | * Output: 24 15 | * Note: 16 | * The length of the given array will be in range [3,104] and all elements are in the range [-1000, 1000]. 17 | * Multiplication of any three numbers in the input won't exceed the range of 32-bit signed integer. 18 | */ 19 | public class MaxProductOfThreeNumbers { 20 | public static void main(String[] args) { 21 | int[] A = {1, 2, 3}; 22 | System.out.println(new MaxProductOfThreeNumbers().maximumProduct(A)); 23 | } 24 | 25 | public int maximumProduct(int[] nums) { 26 | Arrays.sort(nums); 27 | int prod1 = nums[nums.length - 1] * nums[nums.length - 2] * nums[nums.length - 3]; 28 | int prod2 = nums[nums.length - 1] * nums[0] * nums[1]; 29 | return prod1 > prod2 ? prod1 : prod2; 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /problems/src/greedy/JumpGame.java: -------------------------------------------------------------------------------- 1 | package greedy; 2 | 3 | /** 4 | * Created by gouthamvidyapradhan on 17/03/2017. 5 | * Given an array of non-negative integers, you are initially positioned at the first index of the array. 6 | *
7 | * Each element in the array represents your maximum jump length at that position. 8 | *
9 | * Determine if you are able to reach the last index. 10 | *
11 | * For example: 12 | * A = [2,3,1,1,4], return true. 13 | *
14 | * A = [3,2,1,0,4], return false. 15 | */ 16 | public class JumpGame { 17 | /** 18 | * Main method 19 | * 20 | * @param args 21 | * @throws Exception 22 | */ 23 | public static void main(String[] args) throws Exception { 24 | int[] nums = {1, 2, 1, 0, 4}; 25 | System.out.println(new JumpGame().canJump(nums)); 26 | } 27 | 28 | public boolean canJump(int[] nums) { 29 | if (nums.length == 0) return false; 30 | int min = nums.length - 1, max = nums.length - 1; 31 | for (int i = nums.length - 2; i >= 0; i--) { 32 | if ((nums[i] + i) >= min) 33 | min = i; 34 | } 35 | return (min == 0); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /problems/src/bit_manipulation/HammingDistance.java: -------------------------------------------------------------------------------- 1 | package bit_manipulation; 2 | 3 | /** 4 | * Created by gouthamvidyapradhan on 16/12/2017. 5 | * The Hamming distance between two integers is the number of positions at which the corresponding bits are different. 6 | 7 | Given two integers x and y, calculate the Hamming distance. 8 | 9 | Note: 10 | 0 ≤ x, y < 231. 11 | 12 | Example: 13 | 14 | Input: x = 1, y = 4 15 | 16 | Output: 2 17 | 18 | Explanation: 19 | 1 (0 0 0 1) 20 | 4 (0 1 0 0) 21 | ↑ ↑ 22 | 23 | The above arrows point to positions where the corresponding bits are different. 24 | 25 | Solution O(1): XOR (x, y) and count the number of bits set 26 | 27 | */ 28 | public class HammingDistance { 29 | 30 | /** 31 | * Main method 32 | * @param args 33 | * @throws Exception 34 | */ 35 | public static void main(String[] args) throws Exception{ 36 | 37 | } 38 | 39 | public int hammingDistance(int x, int y) { 40 | int z = (x ^ y); 41 | int count = 0; 42 | for(int i = 0; i < 31; i++){ 43 | if((z & (1 << i)) > 0){ 44 | count++; 45 | } 46 | } 47 | return count; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /problems/src/math/CountPrimes.java: -------------------------------------------------------------------------------- 1 | package math; 2 | 3 | import java.util.BitSet; 4 | 5 | /** 6 | * Created by gouthamvidyapradhan on 21/03/2017. 7 | * Description: 8 | *
9 | * Count the number of prime numbers less than a non-negative number, n. 10 | */ 11 | public class CountPrimes { 12 | /** 13 | * Main method 14 | * 15 | * @param args 16 | * @throws Exception 17 | */ 18 | public static void main(String[] args) throws Exception { 19 | System.out.println(new CountPrimes().countPrimes(999187)); 20 | } 21 | 22 | public int countPrimes(int n) { 23 | if (n == 0 || n == 1 || n == 2) return 0; 24 | else if (n == 3) return 1; 25 | BitSet set = new BitSet(); 26 | n = n - 1; 27 | int sqRt = (int) Math.sqrt(n); 28 | int count = n; 29 | for (int i = 2; i <= sqRt; i++) { 30 | if (!set.get(i)) { 31 | for (int j = 2; (i * j) <= n; j++) { 32 | if (!set.get(i * j)) { 33 | count--; 34 | set.set(i * j); 35 | } 36 | } 37 | } 38 | } 39 | return count - 1; 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /problems/src/dynamic_programming/UniqueBinarySearchTrees.java: -------------------------------------------------------------------------------- 1 | package dynamic_programming; 2 | 3 | /** 4 | * Created by gouthamvidyapradhan on 31/03/2017. 5 | * Given n, how many structurally unique BST's (binary search trees) that store values 1...n? 6 | *
7 | * For example, 8 | * Given n = 3, there are a total of 5 unique BST's. 9 | *
10 | * 1 3 3 2 1 11 | * \ / / / \ \ 12 | * 3 2 1 1 3 2 13 | * / / \ \ 14 | * 2 1 2 3 15 | */ 16 | public class UniqueBinarySearchTrees { 17 | int[] dp; 18 | 19 | /** 20 | * Main method 21 | * 22 | * @param args 23 | */ 24 | public static void main(String[] args) throws Exception { 25 | System.out.println(new UniqueBinarySearchTrees().numTrees(5)); 26 | } 27 | 28 | public int numTrees(int n) { 29 | dp = new int[n + 1]; 30 | dp[0] = 1; 31 | return dp(n); 32 | } 33 | 34 | private int dp(int n) { 35 | if (dp[n] != 0) return dp[n]; 36 | for (int i = 1; i <= n; i++) { 37 | dp[n] += dp(n - i) * dp(n - (n - i) - 1); 38 | } 39 | return dp[n]; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /problems/src/math/ExcelSheetColumnTitle.java: -------------------------------------------------------------------------------- 1 | package math; 2 | 3 | /** 4 | * Created by gouthamvidyapradhan on 12/08/2017. 5 | * Given a positive integer, return its corresponding column title as appear in an Excel sheet. 6 | *
7 | * For example: 8 | *
9 | * 1 -> A 10 | * 2 -> B 11 | * 3 -> C 12 | * ... 13 | * 26 -> Z 14 | * 27 -> AA 15 | * 28 -> AB 16 | */ 17 | public class ExcelSheetColumnTitle { 18 | 19 | private static final String CONST = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; 20 | 21 | /** 22 | * Main method 23 | * 24 | * @param args 25 | * @throws Exception 26 | */ 27 | public static void main(String[] args) throws Exception { 28 | System.out.println(new ExcelSheetColumnTitle().convertToTitle(52)); 29 | } 30 | 31 | 32 | public String convertToTitle(int n) { 33 | StringBuilder ans = new StringBuilder(); 34 | while (n > 0) { 35 | int mod = n % 26; 36 | n /= 26; 37 | if (mod == 0) { 38 | ans.append('Z'); 39 | n -= 1; 40 | } else { 41 | ans.append(CONST.charAt(mod - 1)); 42 | } 43 | } 44 | return ans.reverse().toString(); 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /problems/src/string/FirstUniqueCharacterInAString.java: -------------------------------------------------------------------------------- 1 | package string; 2 | 3 | /** 4 | * Created by gouthamvidyapradhan on 09/03/2017. 5 | * Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1. 6 | *
7 | * Examples: 8 | *
9 | * s = "leetcode" 10 | * return 0. 11 | *
12 | * s = "loveleetcode",
13 | * return 2.
14 | * Note: You may assume the string contain only lowercase letters.
15 | */
16 | public class FirstUniqueCharacterInAString {
17 | int[] CHAR = new int[256];
18 |
19 | /**
20 | * Main method
21 | *
22 | * @param args
23 | * @throws Exception
24 | */
25 | public static void main(String[] args) throws Exception {
26 | System.out.println(new FirstUniqueCharacterInAString().firstUniqChar("loveleetcode"));
27 | }
28 |
29 | public int firstUniqChar(String s) {
30 | if (s == null || s.isEmpty()) return -1;
31 |
32 | for (int i = 0, l = s.length(); i < l; i++)
33 | CHAR[s.charAt(i)]++;
34 |
35 | for (int i = 0, l = s.length(); i < l; i++) {
36 | if (CHAR[s.charAt(i)] == 1)
37 | return i;
38 | }
39 |
40 | return -1;
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/problems/src/tree/SumofLeftLeaves.java:
--------------------------------------------------------------------------------
1 | package tree;
2 |
3 | /**
4 | * Created by gouthamvidyapradhan on 13/12/2017.
5 | * Find the sum of all left leaves in a given binary tree.
6 |
7 | Example:
8 |
9 | 3
10 | / \
11 | 9 20
12 | / \
13 | 15 7
14 |
15 | There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.
16 |
17 | */
18 | public class SumofLeftLeaves {
19 |
20 | public class TreeNode {
21 | int val;
22 | TreeNode left;
23 | TreeNode right;
24 | TreeNode(int x) { val = x; }
25 | }
26 |
27 | /**
28 | * Main method
29 | * @param args
30 | * @throws Exception
31 | */
32 | public static void main(String[] args) throws Exception{
33 |
34 | }
35 |
36 | public int sumOfLeftLeaves(TreeNode root) {
37 | return inorder(root, false);
38 | }
39 |
40 | private int inorder(TreeNode node, boolean isLeft){
41 | if(node != null){
42 | if(node.left == null && node.right == null){
43 | if(isLeft){
44 | return node.val;
45 | } else return 0;
46 | }
47 | return inorder(node.left, true) + inorder(node.right, false);
48 | } return 0;
49 | }
50 |
51 | }
52 |
--------------------------------------------------------------------------------
/problems/src/tree/BinaryTreePaths.java:
--------------------------------------------------------------------------------
1 | package tree;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | /**
7 | * Created by gouthamvidyapradhan on 09/12/2017.
8 | * Given a binary tree, return all root-to-leaf paths.
9 |
10 | For example, given the following binary tree:
11 |
12 | 1
13 | / \
14 | 2 3
15 | \
16 | 5
17 | All root-to-leaf paths are:
18 |
19 | ["1->2->5", "1->3"]
20 | */
21 | public class BinaryTreePaths {
22 |
23 | public class TreeNode {
24 | int val;
25 | TreeNode left;
26 | TreeNode right;
27 | TreeNode(int x) { val = x; }
28 | }
29 |
30 | public List
7 | * Each element in the array represents your maximum jump length at that position.
8 | *
9 | * Your goal is to reach the last index in the minimum number of jumps.
10 | *
11 | * For example:
12 | * Given array A = [2,3,1,1,4]
13 | *
14 | * The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.)
15 | *
16 | * Note:
17 | * You can assume that you can always reach the last index.
18 | */
19 | public class JumpGameII {
20 | /**
21 | * Main method
22 | *
23 | * @param args
24 | * @throws Exception
25 | */
26 | public static void main(String[] args) throws Exception {
27 |
28 | }
29 |
30 | public int jump(int[] nums) {
31 | int step = 0;
32 | int e = 0, max = 0;
33 | for (int i = 0; i < nums.length - 1; i++) {
34 | max = Math.max(max, i + nums[i]);
35 | if (i == e) {
36 | step++;
37 | e = max;
38 | }
39 | }
40 | return step;
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/problems/src/dynamic_programming/MaximumProductSubarray.java:
--------------------------------------------------------------------------------
1 | package dynamic_programming;
2 |
3 | /**
4 | * Created by gouthamvidyapradhan on 02/04/2017.
5 | * Find the contiguous subarray within an array (containing at least one number) which has the largest product.
6 | *
7 | * For example, given the array [2,3,-2,4],
8 | * the contiguous subarray [2,3] has the largest product = 6.
9 | */
10 | public class MaximumProductSubarray {
11 | /**
12 | * Main method
13 | *
14 | * @param args
15 | * @throws Exception
16 | */
17 | public static void main(String[] args) throws Exception {
18 | int[] A = {2, 3, -2, 4};
19 | System.out.println(new MaximumProductSubarray().maxProduct(A));
20 | }
21 |
22 | public int maxProduct(int[] nums) {
23 | if (nums.length == 1) return nums[0];
24 | int min = nums[0];
25 | int max = nums[0];
26 | int result = max;
27 | for (int i = 1; i < nums.length; i++) {
28 | int prevMin = min, prevMax = max;
29 | min = Math.min(nums[i], Math.min(nums[i] * prevMin, nums[i] * prevMax));
30 | max = Math.max(nums[i], Math.max(nums[i] * prevMin, nums[i] * prevMax));
31 | result = Math.max(result, max);
32 | }
33 | return result;
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/problems/src/two_pointers/RemoveDuplicates.java:
--------------------------------------------------------------------------------
1 | package two_pointers;
2 |
3 | /**
4 | * Created by gouthamvidyapradhan on 04/07/2017.
5 | * Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.
6 | *
7 | * Do not allocate extra space for another array, you must do this in place with constant memory.
8 | *
9 | * For example,
10 | * Given input array nums = [1,1,2],
11 | *
12 | * 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.
13 | */
14 | public class RemoveDuplicates {
15 | public static void main(String[] args) throws Exception {
16 | int[] nums = {1, 1, 2};
17 | int N = new RemoveDuplicates().removeDuplicates(nums);
18 | for (int i = 0; i < N; i++)
19 | System.out.print(nums[i] + " ");
20 | }
21 |
22 | public int removeDuplicates(int[] nums) {
23 | if (nums.length == 1) return 1;
24 | int size = 1;
25 | for (int j = 0, i = 1; i < nums.length; i++) {
26 | if (nums[i] != nums[i - 1]) {
27 | size++;
28 | j++;
29 | nums[j] = nums[i];
30 | }
31 | }
32 | return size;
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/problems/src/two_pointers/MoveZeroes.java:
--------------------------------------------------------------------------------
1 | package two_pointers;
2 |
3 | /**
4 | * Created by gouthamvidyapradhan on 13/06/2017.
5 | * Accepted
6 | * 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.
7 | *
8 | * For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].
9 | *
10 | * Note:
11 | * You must do this in-place without making a copy of the array.
12 | * Minimize the total number of operations.
13 | */
14 | public class MoveZeroes {
15 | public static void main(String[] args) throws Exception {
16 | int[] nums = {0, 0, 0, 0, 1, 0, 1, 0, 2};
17 | new MoveZeroes().moveZeroes(nums);
18 | for (int n : nums)
19 | System.out.print(n);
20 | }
21 |
22 | public void moveZeroes(int[] nums) {
23 | int i = 0;
24 | for (int j = 0, l = nums.length; j < l; ) {
25 | if (nums[j] == 0)
26 | j++;
27 | else {
28 | int temp = nums[i];
29 | nums[i] = nums[j];
30 | nums[j] = temp;
31 | i++;
32 | j++;
33 | }
34 | }
35 | while (i < nums.length)
36 | nums[i++] = 0;
37 | }
38 |
39 | }
40 |
--------------------------------------------------------------------------------
/problems/src/two_pointers/RemoveDuplicatesII.java:
--------------------------------------------------------------------------------
1 | package two_pointers;
2 |
3 | /**
4 | * Created by gouthamvidyapradhan on 20/01/2018.
5 | * Follow up for "Remove Duplicates":
6 | What if duplicates are allowed at most twice?
7 |
8 | For example,
9 | Given sorted array nums = [1,1,1,2,2,3],
10 |
11 | Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3. It doesn't
12 | matter what you leave beyond the new length.
13 | */
14 | public class RemoveDuplicatesII {
15 |
16 | /**
17 | * Main method
18 | * @param args
19 | * @throws Exception
20 | */
21 | public static void main(String[] args) throws Exception{
22 | int[] A = {1, 1, 1, 2, 2, 2, 3, 4, 4};
23 | System.out.println(new RemoveDuplicatesII().removeDuplicates(A));
24 | }
25 |
26 | public int removeDuplicates(int[] nums) {
27 | if(nums.length == 0) return 0;
28 | int j = 0;
29 | int count = 1;
30 | for(int i = 1; i < nums.length; i++){
31 | if(nums[i - 1] == nums[i]){
32 | count ++;
33 | } else{
34 | count = 1;
35 | }
36 | if(count == 1 || count == 2){
37 | j++;
38 | nums[j] = nums[i];
39 | }
40 | }
41 | return j + 1;
42 | }
43 |
44 | }
45 |
--------------------------------------------------------------------------------
/problems/src/string/ImplementStrStr.java:
--------------------------------------------------------------------------------
1 | package string;
2 |
3 | /**
4 | * Created by gouthamvidyapradhan on 24/06/2017.
5 | * Implement strStr().
6 | *
7 | * Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
8 | *
9 | * Solution O(N ^ 2)
10 | */
11 | public class ImplementStrStr {
12 | public static void main(String[] args) throws Exception {
13 | System.out.println(new ImplementStrStr().strStr("AABB", ""));
14 | }
15 |
16 | public int strStr(String haystack, String needle) {
17 | if (haystack.isEmpty() && needle.isEmpty()) return 0;
18 | if (needle.isEmpty()) return 0;
19 | for (int i = 0, l = haystack.length(); i < l; i++) {
20 | if (haystack.charAt(i) == needle.charAt(0)) {
21 | if (isEqual(haystack, needle, i))
22 | return i;
23 | }
24 | }
25 | return -1;
26 | }
27 |
28 | private boolean isEqual(String haystack, String needle, int i) {
29 | int hL = haystack.length();
30 | int nL = needle.length();
31 | int j = 0;
32 | while (i < hL && j < nL) {
33 | if (haystack.charAt(i) != needle.charAt(j))
34 | return false;
35 | i++;
36 | j++;
37 | }
38 | return j >= nL;
39 | }
40 |
41 |
42 | }
43 |
--------------------------------------------------------------------------------
/problems/src/array/ProductOfArrayExceptSelf.java:
--------------------------------------------------------------------------------
1 | package array;
2 |
3 | /**
4 | * Created by gouthamvidyapradhan on 04/05/2017.
5 | *
6 | * 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].
7 | *
8 | * Solve it without division and in O(n).
9 | *
10 | * For example, given [1,2,3,4], return [24,12,8,6].
11 | *
12 | * Follow up:
13 | * 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.)
14 | */
15 |
16 | public class ProductOfArrayExceptSelf {
17 | public static void main(String[] args) {
18 | int[] nums = {1, 2, 3, 4};
19 | int[] result = new ProductOfArrayExceptSelf().productExceptSelf(nums);
20 | for (int r : result)
21 | System.out.print(r + " ");
22 | }
23 |
24 | public int[] productExceptSelf(int[] nums) {
25 | int[] result = new int[nums.length];
26 | for (int i = 0, temp = 1, l = nums.length; i < l; i++) {
27 | result[i] = temp;
28 | temp *= nums[i];
29 | }
30 | for (int i = nums.length - 1, temp = 1; i >= 0; i--) {
31 | result[i] = result[i] * temp;
32 | temp *= nums[i];
33 | }
34 | return result;
35 | }
36 |
37 | }
38 |
--------------------------------------------------------------------------------
/problems/src/binary_search/MinSortedRotatedArray.java:
--------------------------------------------------------------------------------
1 | package binary_search;
2 |
3 | /**
4 | * Created by gouthamvidyapradhan on 10/04/2017.
5 | * Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
6 | *
7 | * (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
8 | *
9 | * Find the minimum element.
10 | *
11 | * You may assume no duplicate exists in the array.
12 | */
13 | public class MinSortedRotatedArray {
14 | /**
15 | * Main method
16 | *
17 | * @param args
18 | * @throws Exception
19 | */
20 | public static void main(String[] args) throws Exception {
21 | int[] A = {5, 1, 2, 3, 4};
22 | System.out.println(new MinSortedRotatedArray().findMin(A));
23 | }
24 |
25 | public int findMin(int[] nums) {
26 | if (nums.length == 0) return 0;
27 | else if (nums.length == 1) return nums[0];
28 | int low = 0, high = nums.length - 1;
29 | while (low < high) {
30 | int mid = (low + high) / 2;
31 | if (mid > 0 && nums[mid] < nums[mid - 1])
32 | return nums[mid];
33 | if (nums[low] > nums[mid])
34 | high = mid - 1;
35 | else if (nums[high] < nums[mid])
36 | low = mid + 1;
37 | else high = mid - 1;
38 | }
39 | return nums[low];
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/problems/src/backtracking/GenerateParentheses.java:
--------------------------------------------------------------------------------
1 | package backtracking;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | /**
7 | * Created by gouthamvidyapradhan on 24/06/2017.
8 | * Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
9 | *
10 | * For example, given n = 3, a solution set is:
11 | *
12 | * [
13 | * "((()))",
14 | * "(()())",
15 | * "(())()",
16 | * "()(())",
17 | * "()()()"
18 | * ]
19 | */
20 | public class GenerateParentheses {
21 | public static void main(String[] args) throws Exception {
22 | System.out.println(new GenerateParentheses().generateParenthesis(4));
23 | }
24 |
25 | public List
9 | * Given a roman numeral, convert it to an integer.
10 | *
11 | * Input is guaranteed to be within the range from 1 to 3999.
12 | */
13 | public class RomanToInteger {
14 | /**
15 | * Main method
16 | *
17 | * @param args
18 | * @throws Exception
19 | */
20 | public static void main(String[] args) throws Exception {
21 | System.out.println(new RomanToInteger().romanToInt("DXCIX"));
22 | }
23 |
24 | public int romanToInt(String s) {
25 | Map
7 | * 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].
8 | *
9 | * Note:
10 | * Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
11 | *
12 | * Hint:
13 | * Could you do it in-place with O(1) extra space?
14 | * Related problem: Reverse Words in a String II
15 | */
16 | public class RotateArray {
17 | /**
18 | * Main method
19 | *
20 | * @param args
21 | * @throws Exception
22 | */
23 | public static void main(String[] args) throws Exception {
24 | int[] A = {1, 2, 3, 4, 5, 6};
25 | new RotateArray().rotate(A, 2);
26 | for (int i : A)
27 | System.out.print(i + " ");
28 | }
29 |
30 | public void rotate(int[] nums, int k) {
31 | k = k % nums.length;
32 | reverse(nums, 0, nums.length - 1);
33 | reverse(nums, 0, k - 1);
34 | reverse(nums, k, nums.length - 1);
35 | }
36 |
37 | private void reverse(int[] nums, int s, int e) {
38 | for (int i = s, j = e; i < j; i++, j--) {
39 | int temp = nums[i];
40 | nums[i] = nums[j];
41 | nums[j] = temp;
42 | }
43 | }
44 |
45 | }
46 |
--------------------------------------------------------------------------------
/problems/src/array/FirstMissingPositive.java:
--------------------------------------------------------------------------------
1 | package array;
2 |
3 | /**
4 | * Created by gouthamvidyapradhan on 24/06/2017.
5 | * Given an unsorted integer array, find the first missing positive integer.
6 | *
7 | * For example,
8 | * Given [1,2,0] return 3,
9 | * and [3,4,-1,1] return 2.
10 | *
11 | * Your algorithm should run in O(n) time and uses constant space.
12 | */
13 | public class FirstMissingPositive {
14 | private int L;
15 |
16 | public static void main(String[] args) throws Exception {
17 | int[] nums = {1, 3, 5, 9};
18 | System.out.println(new FirstMissingPositive().firstMissingPositive(nums));
19 | }
20 |
21 | public int firstMissingPositive(int[] nums) {
22 | L = nums.length;
23 | for (int i = 0; i < L; i++) {
24 | if (nums[i] > 0 && nums[i] <= L && nums[i] != i + 1) {
25 | int v = nums[i];
26 | nums[i] = -1;
27 | replace(v, nums);
28 | }
29 | }
30 |
31 | for (int i = 0; i < L; i++) {
32 | if (nums[i] != i + 1)
33 | return i + 1;
34 | }
35 |
36 | return L + 1;
37 | }
38 |
39 | private void replace(int i, int[] nums) {
40 | if (i > 0 && i <= L && i != nums[i - 1]) {
41 | int v = nums[i - 1];
42 | nums[i - 1] = i;
43 | replace(v, nums);
44 | }
45 | }
46 |
47 | }
48 |
--------------------------------------------------------------------------------
/problems/src/backtracking/Subsets.java:
--------------------------------------------------------------------------------
1 | package backtracking;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | /**
7 | * Created by gouthamvidyapradhan on 14/03/2017.
8 | * Given a set of distinct integers, nums, return all possible subsets.
9 | *
10 | * Note: The solution set must not contain duplicate subsets.
11 | *
12 | * For example,
13 | * If nums = [1,2,3], a solution is:
14 | *
15 | * [
16 | * [3],
17 | * [1],
18 | * [2],
19 | * [1,2,3],
20 | * [1,3],
21 | * [2,3],
22 | * [1,2],
23 | * []
24 | * ]
25 | */
26 | public class Subsets {
27 | /**
28 | * Main method
29 | *
30 | * @param args
31 | * @throws Exception
32 | */
33 | public static void main(String[] args) throws Exception {
34 | int[] n = {1, 2, 3};
35 | List
7 | * 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.
8 | */
9 | public class HouseRobber {
10 | private int[] max;
11 |
12 | /**
13 | * Main method
14 | *
15 | * @param args
16 | * @throws Exception
17 | */
18 | public static void main(String[] args) throws Exception {
19 |
20 | }
21 |
22 | public int rob(int[] nums) {
23 | if (nums.length == 0) return 0;
24 | max = new int[nums.length];
25 | if (nums.length == 1) return nums[0];
26 | max[nums.length - 1] = nums[nums.length - 1];
27 | max[nums.length - 2] = Math.max(nums[nums.length - 1], nums[nums.length - 2]);
28 | for (int i = nums.length - 3; i >= 0; i--) {
29 | max[i] = Math.max(max[i + 1], nums[i] + max[i + 2]);
30 | }
31 | return max[0];
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/problems/src/hashing/ValidAnagram.java:
--------------------------------------------------------------------------------
1 | package hashing;
2 |
3 | /**
4 | * Created by gouthamvidyapradhan on 10/03/2017.
5 | * Given two strings s and t, write a function to determine if t is an anagram of s.
6 | *
7 | * For example,
8 | * s = "anagram", t = "nagaram", return true.
9 | * s = "rat", t = "car", return false.
10 | *
11 | * Note:
12 | * You may assume the string contains only lowercase alphabets.
13 | *
14 | * Follow up:
15 | * What if the inputs contain unicode characters? How would you adapt your solution to such case?
16 | */
17 | public class ValidAnagram {
18 | private int[] S = new int[256];
19 | private int[] T = new int[256];
20 |
21 | /**
22 | * Main method
23 | *
24 | * @param args
25 | * @throws Exception
26 | */
27 | public static void main(String[] args) throws Exception {
28 | System.out.println(new ValidAnagram().isAnagram("anagram", "nagaram"));
29 | }
30 |
31 | public boolean isAnagram(String s, String t) {
32 | if (s.length() != t.length()) return false;
33 |
34 | for (int i = 0, l = s.length(); i < l; i++) {
35 | S[s.charAt(i)]++;
36 | }
37 |
38 | for (int i = 0, l = t.length(); i < l; i++) {
39 | T[t.charAt(i)]++;
40 | }
41 |
42 | for (int i = 0; i < 256; i++) {
43 | if (S[i] != T[i]) return false;
44 | }
45 |
46 | return true;
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/problems/src/binary_search/FirstBadVersion.java:
--------------------------------------------------------------------------------
1 | package binary_search;
2 |
3 | /**
4 | * Created by gouthamvidyapradhan on 29/11/2017.
5 | *
6 | * You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version
7 | * of your product fails the quality check. Since each version is developed based on the previous version,
8 | * all the versions after a bad version are also bad.
9 |
10 | Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the
11 | following ones to be bad.
12 |
13 | You are given an API bool isBadVersion(version) which will return whether version is bad. Implement a function to
14 | find the first bad version. You should minimize the number of calls to the API.
15 | */
16 | public class FirstBadVersion {
17 | public static void main(String[] args) throws Exception{
18 | System.out.println(new FirstBadVersion().firstBadVersion(2126753390));
19 | }
20 |
21 | public int firstBadVersion(int n) {
22 | int low = 0, high = n;
23 | while(low < high){
24 | int mid = (low + high) >>> 1;
25 | if(isBadVersion(mid)){
26 | high = mid;
27 | } else low = mid + 1;
28 | }
29 | return high;
30 | }
31 |
32 | private boolean isBadVersion(int n){
33 | if(n >= 1702766719)
34 | return true;
35 | return false;
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/problems/src/array/ReadNCharacters.java:
--------------------------------------------------------------------------------
1 | package array;
2 |
3 | /**
4 | * Created by gouthamvidyapradhan on 09/12/2017.
5 | * The API: int read4(char *buf) reads 4 characters at a time from a file.
6 |
7 | The return value is the actual number of characters read. For example, it returns 3 if there is only 3 characters
8 | left in the file.
9 |
10 | By using the read4 API, implement the function int read(char *buf, int n) that reads n characters from the file.
11 |
12 | Note:
13 | The read function will only be called once for each test case.
14 |
15 |
16 | */
17 | public class ReadNCharacters {
18 |
19 | /**
20 | * Main method
21 | * @param args
22 | */
23 | public static void main(String[] args) {
24 |
25 | }
26 |
27 | /**
28 | *
29 | * @param buf
30 | * @param n
31 | * @return
32 | */
33 | public int read(char[] buf, int n) {
34 | int i = 0;
35 | int toRead = Math.min(n, buf.length);
36 | while(i < toRead){
37 | char[] temp = new char[4];
38 | int r = read4(temp);
39 | for(int j = 0; j < r && i < toRead; j ++){
40 | buf[i] = temp[j];
41 | i++;
42 | }
43 | if(r < 4) break;
44 | }
45 | return Math.min(i, toRead);
46 | }
47 |
48 |
49 | private int read4(char[] buf){
50 | return 1;//return fake value just to resolve compilation error
51 | }
52 |
53 | }
54 |
--------------------------------------------------------------------------------
/problems/src/bit_manipulation/GrayCode.java:
--------------------------------------------------------------------------------
1 | package bit_manipulation;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | /**
7 | * Created by gouthamvidyapradhan on 16/03/2017.
8 | * The gray code is a binary numeral system where two successive values differ in only one bit.
9 | *
10 | * Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray code. A gray code sequence must begin with 0.
11 | *
12 | * For example, given n = 2, return [0,1,3,2]. Its gray code sequence is:
13 | *
14 | * 00 - 0
15 | * 01 - 1
16 | * 11 - 3
17 | * 10 - 2
18 | * Note:
19 | * For a given n, a gray code sequence is not uniquely defined.
20 | *
21 | * For example, [0,2,3,1] is also a valid gray code sequence according to the above definition.
22 | *
23 | * For now, the judge is able to judge based on one instance of gray code sequence. Sorry about that.
24 | */
25 | public class GrayCode {
26 |
27 | /**
28 | * Main method
29 | *
30 | * @param args
31 | * @throws Exception
32 | */
33 | public static void main(String[] args) throws Exception {
34 | List
10 | * For example,
11 | * If n = 4 and k = 2, a solution is:
12 | *
13 | * [
14 | * [2,4],
15 | * [3,4],
16 | * [2,3],
17 | * [1,2],
18 | * [1,3],
19 | * [1,4],
20 | * ]
21 | */
22 | public class Combinations {
23 |
24 | public static void main(String[] args) throws Exception {
25 | List
10 | * Given an index k, return the kth row of the Pascal's triangle.
11 | *
12 | * For example, given k = 3,
13 | * Return [1,3,3,1].
14 | *
15 | * Note:
16 | * Could you optimize your algorithm to use only O(k) extra space?
17 | */
18 | public class PascalsTriangle {
19 | public static void main(String[] args) throws Exception {
20 | System.out.println(new PascalsTriangle().getRow(3));
21 | }
22 |
23 | public List
7 | * For example,
8 | * "A man, a plan, a canal: Panama" is a palindrome.
9 | * "race a car" is not a palindrome.
10 | *
11 | * Note:
12 | * Have you consider that the string might be empty? This is a good question to ask during an interview.
13 | *
14 | * For the purpose of this problem, we define empty string as valid palindrome.
15 | */
16 | public class ValidPalindrome {
17 | public static void main(String[] args) throws Exception {
18 | System.out.println(new ValidPalindrome().isPalindrome("989 "));
19 | }
20 |
21 | public boolean isPalindrome(String s) {
22 | if (s == null || s.isEmpty()) return true;
23 | s = s.toLowerCase();
24 | for (int i = 0, j = s.length() - 1; i < j; ) {
25 | char f = s.charAt(i);
26 | char l = s.charAt(j);
27 | if (!(f >= 'a' && f <= 'z') && !(f >= '0' && f <= '9')) {
28 | i++;
29 | continue;
30 | }
31 | if (!(l >= 'a' && l <= 'z') && !(l >= '0' && l <= '9')) {
32 | j--;
33 | continue;
34 | }
35 | if (f != l)
36 | return false;
37 | i++;
38 | j--;
39 | }
40 | return true;
41 | }
42 |
43 | }
44 |
--------------------------------------------------------------------------------
/problems/src/dynamic_programming/LongestPalindromicSubsequence.java:
--------------------------------------------------------------------------------
1 | package dynamic_programming;
2 |
3 | /**
4 | * Created by gouthamvidyapradhan on 27/03/2017.
5 | * Given an unsorted array of integers, find the length of longest increasing subsequence.
6 | *
7 | * For example,
8 | * Given [10, 9, 2, 5, 3, 7, 101, 18],
9 | * The longest increasing subsequence is [2, 3, 7, 101], therefore the length is 4. Note that there may be more than one LIS combination, it is only necessary for you to return the length.
10 | *
11 | * Your algorithm should run in O(n2) complexity.
12 | *
13 | * Follow up: Could you improve it to O(n log n) time complexity?
14 | */
15 | public class LongestPalindromicSubsequence {
16 | /**
17 | * Main method
18 | *
19 | * @param args
20 | * @throws Exception
21 | */
22 | public static void main(String[] args) throws Exception {
23 | System.out.println(new LongestPalindromicSubsequence().longestPalindromeSubseq("bbbab"));
24 | }
25 |
26 | public int longestPalindromeSubseq(String s) {
27 | int[][] dp = new int[s.length() + 1][s.length() + 1];
28 | String sI = new StringBuilder(s).reverse().toString();
29 | for (int i = 1, l = s.length(); i <= l; i++)
30 | for (int j = 1; j <= l; j++) {
31 | dp[i][j] = (s.charAt(i - 1) == sI.charAt(j - 1)) ? dp[i - 1][j - 1] + 1 : Math.max(dp[i - 1][j], dp[i][j - 1]);
32 | }
33 |
34 | return dp[s.length()][s.length()];
35 | }
36 |
37 | }
38 |
--------------------------------------------------------------------------------
/problems/src/linked_list/DeleteNode.java:
--------------------------------------------------------------------------------
1 | package linked_list;
2 |
3 | /**
4 | * Created by gouthamvidyapradhan on 04/07/2017.
5 | * Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.
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 | public class DeleteNode {
10 | public static class ListNode {
11 | int val;
12 | ListNode next;
13 |
14 | ListNode(int x) {
15 | val = x;
16 | }
17 | }
18 |
19 | public static void main(String[] args) {
20 | ListNode node = new ListNode(1);
21 | node.next = new ListNode(2);
22 | node.next.next = new ListNode(3);
23 | node.next.next.next = new ListNode(4);
24 | new DeleteNode().deleteNode(node.next.next);
25 | while (node != null) {
26 | System.out.println(node.val);
27 | node = node.next;
28 | }
29 | }
30 |
31 | public void deleteNode(ListNode node) {
32 | ListNode prev = node;
33 | ListNode last = node;
34 | ListNode next = node.next;
35 | while (next != null) {
36 | last = prev;
37 | int temp = prev.val;
38 | prev.val = next.val;
39 | next.val = temp;
40 | prev = prev.next;
41 | next = next.next;
42 | }
43 | last.next = null;
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/problems/src/array/MeetingRooms.java:
--------------------------------------------------------------------------------
1 | package array;
2 |
3 | import java.util.Arrays;
4 |
5 | /**
6 | * Created by gouthamvidyapradhan on 27/11/2017.
7 | * 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.
8 |
9 | For example,
10 | Given [[0, 30],[5, 10],[15, 20]],
11 | return false.
12 |
13 | Solution: Sort the interval based on the start interval. Then, for every interval check if the previous interval
14 | ends before the start of the current interval.
15 | */
16 | public class MeetingRooms {
17 |
18 | public static class Interval {
19 | int start;
20 | int end;
21 | Interval() { start = 0; end = 0; }
22 | Interval(int s, int e) { start = s; end = e; }
23 | }
24 |
25 | public static void main(String[] args) throws Exception{
26 | Interval i1 = new Interval(0, 30);
27 | Interval i2 = new Interval(5, 10);
28 | Interval i3 = new Interval(15, 20);
29 | Interval[] intervals = {i1, i2, i3};
30 |
31 | System.out.println(new MeetingRooms().canAttendMeetings(intervals));
32 | }
33 |
34 | public boolean canAttendMeetings(Interval[] intervals) {
35 | Arrays.sort(intervals, (a, b) -> Integer.compare(a.start, b.start));
36 | for(int i = 1; i < intervals.length; i ++){
37 | if(intervals[i].start < intervals[i - 1].end)
38 | return false;
39 | }
40 | return true;
41 | }
42 |
43 | }
44 |
--------------------------------------------------------------------------------
/problems/src/array/RotateMatrix.java:
--------------------------------------------------------------------------------
1 | package array;
2 |
3 | /**
4 | * Created by gouthamvidyapradhan on 21/03/2017.
5 | * You are given an n x n 2D matrix representing an image.
6 | *
7 | * Rotate the image by 90 degrees (clockwise).
8 | *
9 | * Follow up:
10 | * Could you do this in-place?
11 | */
12 | public class RotateMatrix {
13 | /**
14 | * Main method
15 | *
16 | * @param args
17 | * @throws Exception
18 | */
19 | public static void main(String[] args) throws Exception {
20 | int[][] A = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
21 | new RotateMatrix().rotate(A);
22 | for (int i = 0; i < A.length; i++) {
23 | for (int j = 0; j < A[0].length; j++) {
24 | System.out.println(A[i][j]);
25 | }
26 | }
27 | }
28 |
29 | public void rotate(int[][] matrix) {
30 | int lc = 0, tr = 0, rc = matrix[0].length - 1, br = matrix.length - 1;
31 | while (tr < br) {
32 | for (int i = lc, j = tr, k = rc, l = br; i < rc && j < br && k > lc && l > tr; i++, j++, k--, l--) {
33 | int temp1 = matrix[j][rc];
34 | matrix[j][rc] = matrix[tr][i];
35 | int temp2 = matrix[br][k];
36 | matrix[br][k] = temp1;
37 | temp1 = matrix[l][lc];
38 | matrix[l][lc] = temp2;
39 | matrix[tr][i] = temp1;
40 | }
41 | lc++;
42 | tr++;
43 | rc--;
44 | br--;
45 | }
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/problems/src/bit_manipulation/DivideTwoIntegers.java:
--------------------------------------------------------------------------------
1 | package bit_manipulation;
2 |
3 | /**
4 | * Created by gouthamvidyapradhan on 13/02/2018.
5 | * Divide two integers without using multiplication, division and mod operator.
6 |
7 | If it is overflow, return MAX_INT.
8 | */
9 | public class DivideTwoIntegers {
10 |
11 | /**
12 | * Main method
13 | * @param args
14 | * @throws Exception
15 | */
16 | public static void main(String[] args) throws Exception{
17 | System.out.println(new DivideTwoIntegers().divide(0, 775));
18 | }
19 |
20 | public int divide(int dividend, int divisor) {
21 | if(divisor == 0) return Integer.MAX_VALUE;
22 | else if(dividend == Integer.MIN_VALUE && divisor == -1) return Integer.MAX_VALUE;
23 | else if(divisor == 1) return dividend;
24 | boolean isNegative = ((dividend < 0 && divisor > 0) || (dividend > 0 && divisor < 0));
25 | dividend = (dividend < 0)? -dividend : dividend;
26 | divisor = (divisor < 0) ? -divisor : divisor;
27 | int sum, result = 0;
28 | while(true){
29 | int d1 = divisor;
30 | sum = 0;
31 | if(dividend - d1 == 0) {sum += 1; result += sum; break;}
32 | if(dividend - d1 < 0) break;
33 | while(dividend - (d1 << 1) > 0){
34 | d1 <<= 1;
35 | sum += 1;
36 | }
37 | result += (1 << sum);
38 | dividend = dividend - d1;
39 | }
40 | return isNegative ? -result : result;
41 | }
42 |
43 | }
44 |
--------------------------------------------------------------------------------
/problems/src/dynamic_programming/LongestIncreasingSubsequence.java:
--------------------------------------------------------------------------------
1 | package dynamic_programming;
2 |
3 | /**
4 | * Created by gouthamvidyapradhan on 02/04/2017.
5 | * Given an unsorted array of integers, find the length of longest increasing subsequence.
6 | *
7 | * For example,
8 | * Given [10, 9, 2, 5, 3, 7, 101, 18],
9 | * The longest increasing subsequence is [2, 3, 7, 101], therefore the length is 4. Note that there may be more than one LIS combination, it is only necessary for you to return the length.
10 | *
11 | * Your algorithm should run in O(n2) complexity.
12 | *
13 | * Follow up: Could you improve it to O(n log n) time complexity?
14 | */
15 | public class LongestIncreasingSubsequence {
16 | /**
17 | * Main method
18 | *
19 | * @param args
20 | * @throws Exception
21 | */
22 | public static void main(String[] args) throws Exception {
23 | int[] nums = {9, 8, 7, 6};
24 | System.out.println(new LongestIncreasingSubsequence().lengthOfLIS(nums));
25 | }
26 |
27 | public int lengthOfLIS(int[] nums) {
28 | if (nums.length == 0) return 0;
29 | int[] A = new int[nums.length];
30 | int max = Integer.MIN_VALUE;
31 | for (int i = 0, l = nums.length; i < l; i++) {
32 | int lis = 1;
33 | for (int j = 0; j < i; j++) {
34 | if (nums[i] > nums[j])
35 | lis = Math.max(lis, A[j] + 1);
36 | }
37 | A[i] = lis;
38 | max = Math.max(max, A[i]);
39 | }
40 | return max;
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/problems/src/tree/MinimumAbsoluteDifferenceInBST.java:
--------------------------------------------------------------------------------
1 | package tree;
2 |
3 | /**
4 | * Created by gouthamvidyapradhan on 15/02/2018.
5 | * Given a binary search tree with non-negative values, find the minimum absolute difference between values of any
6 | * two nodes.
7 |
8 | Example:
9 |
10 | Input:
11 |
12 | 1
13 | \
14 | 3
15 | /
16 | 2
17 |
18 | Output:
19 | 1
20 |
21 | Explanation:
22 | The minimum absolute difference is 1, which is the difference between 2 and 1 (or between 2 and 3).
23 | Note: There are at least two nodes in this BST.
24 | */
25 | public class MinimumAbsoluteDifferenceInBST {
26 |
27 | public static class TreeNode {
28 | int val;
29 | TreeNode left;
30 | TreeNode right;
31 | TreeNode(int x) { val = x; }
32 | }
33 |
34 | int min = Integer.MAX_VALUE;
35 |
36 | public static void main(String[] args) throws Exception{
37 | TreeNode root = new TreeNode(1);
38 | root.right = new TreeNode(2);
39 | root.right.right = new TreeNode(3);
40 | new MinimumAbsoluteDifferenceInBST().getMinimumDifference(root);
41 | }
42 |
43 | public int getMinimumDifference(TreeNode root) {
44 | getMin(root, null);
45 | return min;
46 | }
47 |
48 | private Integer getMin(TreeNode node, Integer prev){
49 | if(node == null) return prev;
50 | Integer left = getMin(node.left, prev);
51 | if(left != null){
52 | min = Math.min(min, Math.abs(node.val - left));
53 | }
54 | return getMin(node.right, node.val);
55 | }
56 |
57 | }
58 |
--------------------------------------------------------------------------------
/problems/src/string/AddBinary.java:
--------------------------------------------------------------------------------
1 | package string;
2 |
3 | /**
4 | * Created by gouthamvidyapradhan on 25/11/2017.
5 | *
6 | * Given two binary strings, return their sum (also a binary string).
7 |
8 | For example,
9 | a = "11"
10 | b = "1"
11 | Return "100".
12 | */
13 | public class AddBinary {
14 |
15 | /**
16 | * Main method
17 | * @param args
18 | */
19 | public static void main(String[] args) {
20 | System.out.println(new AddBinary().addBinary("000001010000101001", "0"));
21 | }
22 |
23 | public String addBinary(String a, String b) {
24 | if(a.length() > b.length()){
25 | return calculate(a, b);
26 | } else return calculate(b, a);
27 | }
28 |
29 | /**
30 | * Calculate sum
31 | * @param a length of a should always be greater or equal to b
32 | * @param b length of b should always be smaller of equal to a
33 | * @return
34 | */
35 | private String calculate(String a, String b){
36 | int carry = 0;
37 | int d = a.length() - b.length();
38 | StringBuilder sb = new StringBuilder();
39 | for(int i = a.length() - 1; i >= 0; i --){
40 | int first = Integer.parseInt(String.valueOf(a.charAt(i)));
41 | int second = i - d >= 0 ? Integer.parseInt(String.valueOf(b.charAt(i - d))) : 0;
42 | int sum = (first + second + carry);
43 | carry = sum / 2;
44 | sb.append(sum % 2);
45 | }
46 | if(carry != 0)
47 | sb.append(carry);
48 | return sb.reverse().toString();
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/problems/src/tree/SymmetricTree.java:
--------------------------------------------------------------------------------
1 | package tree;
2 |
3 | /**
4 | * Created by gouthamvidyapradhan on 14/08/2017.
5 | * Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
6 | *
7 | * For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
8 | *
9 | * 1
10 | * / \
11 | * 2 2
12 | * / \ / \
13 | * 3 4 4 3
14 | *
15 | * But the following [1,2,2,null,3,null,3] is not:
16 | * 1
17 | * / \
18 | * 2 2
19 | * \ \
20 | * 3 3
21 | */
22 | public class SymmetricTree {
23 |
24 | static class TreeNode {
25 | int val;
26 | TreeNode left;
27 | TreeNode right;
28 |
29 | TreeNode(int x) {
30 | val = x;
31 | }
32 | }
33 |
34 | /**
35 | * Main method
36 | *
37 | * @param args
38 | * @throws Exception
39 | */
40 | public static void main(String[] args) throws Exception {
41 | TreeNode node = new TreeNode(3);
42 | node.left = new TreeNode(4);
43 | node.right = new TreeNode(5);
44 | System.out.println(new SymmetricTree().isSymmetric(node));
45 | }
46 |
47 | public boolean isSymmetric(TreeNode root) {
48 | if (root == null) return true;
49 | return dfs(root.left, root.right);
50 | }
51 |
52 | private boolean dfs(TreeNode left, TreeNode right) {
53 | if (left == null && right == null) return true;
54 | else if (left == null || right == null) return false;
55 | return dfs(left.left, right.right) && left.val == right.val && dfs(left.right, right.left);
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/problems/src/binary_search/SearchRotatedSortedArray.java:
--------------------------------------------------------------------------------
1 | package binary_search;
2 |
3 | /**
4 | * Created by gouthamvidyapradhan on 10/04/2017.
5 | * Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
6 | *
7 | * (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
8 | *
9 | * You are given a target value to search. If found in the array return its index, otherwise return -1.
10 | *
11 | * You may assume no duplicate exists in the array.
12 | */
13 | public class SearchRotatedSortedArray {
14 | /**
15 | * Main method
16 | *
17 | * @param args
18 | * @throws Exception
19 | */
20 | public static void main(String[] args) throws Exception {
21 | int[] A = {5, 4, 3, 2, 1};
22 | System.out.println(new SearchRotatedSortedArray().search(A, 4));
23 | }
24 |
25 | public int search(int[] nums, int target) {
26 | if (nums.length == 0) return -1;
27 | if (nums.length == 1) {
28 | return (nums[0] == target) ? 0 : -1;
29 | }
30 | int low = 0, high = nums.length - 1;
31 | while (low < high) {
32 | int mid = (low + high) >>> 1;
33 | if (nums[mid] == target)
34 | return mid;
35 | if ((nums[mid] <= nums[low]) && (target > nums[mid] && target <= nums[high]) ||
36 | (nums[low] <= nums[mid] && (target < nums[low] || target > nums[mid])))
37 | low = mid + 1;
38 | else high = mid - 1;
39 | }
40 | return (nums[low] == target) ? low : -1;
41 | }
42 |
43 | }
44 |
--------------------------------------------------------------------------------
/problems/src/greedy/QueueReconstructionByHeight.java:
--------------------------------------------------------------------------------
1 | package greedy;
2 |
3 | import java.util.Arrays;
4 | import java.util.LinkedList;
5 |
6 | /**
7 | * Created by gouthamvidyapradhan on 29/06/2017.
8 | * Suppose you have a random list of people standing in a queue. Each person is described by a pair of integers (h, k), where h is the height of the person and k is the number of people in front of this person who have a height greater than or equal to h. Write an algorithm to reconstruct the queue.
9 | *
10 | * Note:
11 | * The number of people is less than 1,100.
12 | *
13 | * Example
14 | *
15 | * Input:
16 | * [[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]
17 | *
18 | * Output:
19 | * [[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]
20 | */
21 | public class QueueReconstructionByHeight {
22 | public static void main(String[] args) throws Exception {
23 | int[][] A = {{7, 0}, {4, 4}, {7, 1}, {5, 0}, {6, 1}, {5, 2}};
24 | int[][] r = new QueueReconstructionByHeight().reconstructQueue(A);
25 | for (int[] i : r) {
26 | System.out.println(i[0] + " " + i[1]);
27 | }
28 | }
29 |
30 | public int[][] reconstructQueue(int[][] people) {
31 | Arrays.sort(people, ((o1, o2) -> (o2[0] - o1[0] == 0) ? o1[1] - o2[1] : o2[0] - o1[0]));
32 | LinkedList
10 | * Follow up:
11 | * Can you solve it without using extra space?
12 | */
13 | public class LinkedListCycle {
14 | private static Set
7 | * 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.
8 | *
9 | * You may assume that each input would have exactly one solution and you may not use the same element twice.
10 | *
11 | * Input: numbers={2, 7, 11, 15}, target=9
12 | * Output: index1=1, index2=2
13 | */
14 | public class TwoSumII {
15 | /**
16 | * Main method
17 | *
18 | * @param args
19 | * @throws Exception
20 | */
21 | public static void main(String[] args) throws Exception {
22 | int[] nums = {2, 7, 11, 15};
23 | int[] result = new TwoSumII().twoSum(nums, 23);
24 | for (int i : result)
25 | System.out.println(i);
26 | }
27 |
28 | public int[] twoSum(int[] numbers, int target) {
29 | int i = 0, j = numbers.length - 1;
30 | while (i < j) {
31 | int x = (numbers[i] + numbers[j]);
32 | if (x == target) {
33 | int[] result = new int[2];
34 | result[0] = i + 1;
35 | result[1] = j + 1;
36 | return result;
37 | } else if (x < target)
38 | i++;
39 | else j--;
40 | }
41 | return new int[2];
42 | }
43 |
44 |
45 | }
46 |
--------------------------------------------------------------------------------
/problems/src/tree/TwoSumIV.java:
--------------------------------------------------------------------------------
1 | package tree;
2 |
3 | import java.util.HashSet;
4 |
5 | /**
6 | * Created by gouthamvidyapradhan on 16/12/2017.
7 | * Given a Binary Search Tree and a target number, return true if there exist two elements in the BST such that
8 | * their sum is equal to the given target.
9 |
10 | Example 1:
11 | Input:
12 | 5
13 | / \
14 | 3 6
15 | / \ \
16 | 2 4 7
17 |
18 | Target = 9
19 |
20 | Output: True
21 | Example 2:
22 | Input:
23 | 5
24 | / \
25 | 3 6
26 | / \ \
27 | 2 4 7
28 |
29 | Target = 28
30 |
31 | Output: False
32 | */
33 | public class TwoSumIV {
34 |
35 | public class TreeNode {
36 | int val;
37 | TreeNode left;
38 | TreeNode right;
39 | TreeNode(int x) { val = x; }
40 | }
41 |
42 | /**
43 | * Main method
44 | * @param args
45 | * @throws Exception
46 | */
47 | public static void main(String[] args) throws Exception{
48 | }
49 |
50 | public boolean findTarget(TreeNode root, int k) {
51 | return inorder(root, new HashSet<>(), k);
52 | }
53 |
54 | private boolean inorder(TreeNode node, HashSet
9 | * If z liters of water is measurable, you must have z liters of water contained within one or both buckets by the end.
10 | *
11 | * Operations allowed:
12 | *
13 | * Fill any of the jugs completely with water.
14 | * Empty any of the jugs.
15 | * Pour water from one jug into another till the other jug is completely full or the first jug itself is empty.
16 | * Example 1: (From the famous "Die Hard" example)
17 | *
18 | * Input: x = 3, y = 5, z = 4
19 | * Output: True
20 | * Example 2:
21 | *
22 | * Input: x = 2, y = 6, z = 5
23 | * Output: False
24 | */
25 | public class WaterAndJugProblem {
26 | /**
27 | * Main method
28 | *
29 | * @param args
30 | * @throws Exception
31 | */
32 | public static void main(String[] args) throws Exception {
33 | System.out.println(new WaterAndJugProblem().canMeasureWater(0, 0, 1));
34 | }
35 |
36 | public boolean canMeasureWater(int x, int y, int z) {
37 | if (x == y && y == z) return true;
38 | if (z > (x + y)) return false;
39 | BigInteger b1 = new BigInteger(String.valueOf(x));
40 | BigInteger b2 = new BigInteger(String.valueOf(y));
41 | BigInteger b3 = b1.gcd(b2);
42 | return b3.intValue() != 0 && (z % b3.intValue()) == 0;
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/problems/src/dynamic_programming/DecodeWays.java:
--------------------------------------------------------------------------------
1 | package dynamic_programming;
2 |
3 | /**
4 | * Created by gouthamvidyapradhan on 01/04/2017.
5 | * A message containing letters from A-Z is being encoded to numbers using the following mapping:
6 | *
7 | * 'A' -> 1
8 | * 'B' -> 2
9 | * ...
10 | * 'Z' -> 26
11 | * Given an encoded message containing digits, determine the total number of ways to decode it.
12 | *
13 | * For example,
14 | * Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12).
15 | *
16 | * The number of ways decoding "12" is 2.
17 | */
18 | public class DecodeWays {
19 | /**
20 | * Main method
21 | *
22 | * @param args
23 | * @throws Exception
24 | */
25 | public static void main(String[] args) throws Exception {
26 | System.out.println(new DecodeWays().numDecodings("3120"));
27 | }
28 |
29 | public int numDecodings(String s) {
30 | if (s == null || s.isEmpty()) return 0;
31 | int[] dp = new int[s.length() + 2];
32 | dp[s.length()] = 1;
33 | dp[s.length() + 1] = 1;
34 | for (int i = s.length() - 1; i >= 0; i--) {
35 | for (int j = i + 1; j < i + 3; j++) {
36 | if (j <= s.length()) {
37 | String subStr = s.substring(i, j);
38 | if (!subStr.startsWith("0")) {
39 | int intVal = Integer.parseInt(subStr);
40 | if (intVal <= 26) {
41 | dp[i] += dp[j];
42 | }
43 | }
44 | }
45 | }
46 | }
47 | return dp[0];
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/problems/src/dynamic_programming/TwoKeysKeyboard.java:
--------------------------------------------------------------------------------
1 | package dynamic_programming;
2 |
3 | /**
4 | * Created by gouthamvidyapradhan on 19/08/2017.
5 | * Initially on a notepad only one character 'A' is present. You can perform two operations on this notepad for each step:
6 | *
7 | * Copy All: You can copy all the characters present on the notepad (partial copy is not allowed).
8 | * Paste: You can paste the characters which are copied last time.
9 | * Given a number n. You have to get exactly n 'A' on the notepad by performing the minimum number of steps permitted. Output the minimum number of steps to get n 'A'.
10 | *
11 | * Example 1:
12 | * Input: 3
13 | * Output: 3
14 | * Explanation:
15 | * Intitally, we have one character 'A'.
16 | * In step 1, we use Copy All operation.
17 | * In step 2, we use Paste operation to get 'AA'.
18 | * In step 3, we use Paste operation to get 'AAA'.
19 | *
20 | * Note:
21 | * The n will be in the range [1, 1000].
22 | */
23 | public class TwoKeysKeyboard {
24 | /**
25 | * Main method
26 | *
27 | * @param args
28 | * @throws Exception
29 | */
30 | public static void main(String[] args) throws Exception {
31 | System.out.println(new TwoKeysKeyboard().minSteps(8));
32 | }
33 |
34 | public int minSteps(int n) {
35 | int[] DP = new int[n + 1];
36 | for (int i = 2; i <= n; i++) {
37 | DP[i] = i;
38 | for (int j = 2; j < i; j++) {
39 | if ((i % j) == 0) {
40 | DP[i] = Math.min(DP[i], DP[j] + (i / j));
41 | }
42 | }
43 | }
44 | return DP[n];
45 | }
46 |
47 | }
48 |
--------------------------------------------------------------------------------
/problems/src/backtracking/PermutationsII.java:
--------------------------------------------------------------------------------
1 | package backtracking;
2 |
3 | import java.util.ArrayList;
4 | import java.util.Arrays;
5 | import java.util.List;
6 |
7 | /**
8 | * Created by gouthamvidyapradhan on 12/04/2017.
9 | * Given a collection of numbers that might contain duplicates, return all possible unique permutations.
10 | *
11 | * For example,
12 | * [1,1,2] have the following unique permutations:
13 | * [
14 | * [1,1,2],
15 | * [1,2,1],
16 | * [2,1,1]
17 | * ]
18 | */
19 | public class PermutationsII {
20 | public static void main(String[] args) {
21 | int[] A = {1, 2, 2};
22 | System.out.println(new PermutationsII().permuteUnique(A));
23 | }
24 |
25 | public List
7 | * 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.
8 | *
9 | * Example 1:
10 | * Input: [7, 1, 5, 3, 6, 4]
11 | * Output: 5
12 | *
13 | * max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)
14 | * Example 2:
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 | public class BestTimeToBuyAndSellStocks {
21 | /**
22 | * Main method
23 | *
24 | * @param args
25 | * @throws Exception
26 | */
27 | public static void main(String[] args) throws Exception {
28 | int[] prices = {1, 1, 1, 1, 1};
29 | System.out.println(new BestTimeToBuyAndSellStocks().maxProfit(prices));
30 | }
31 |
32 | public int maxProfit(int[] prices) {
33 | if (prices.length == 0) return 0;
34 | int[] max = new int[prices.length];
35 | max[prices.length - 1] = prices[prices.length - 1];
36 | for (int i = prices.length - 2; i >= 0; i--) {
37 | max[i] = Math.max(prices[i], max[i + 1]);
38 | }
39 | int result = Integer.MIN_VALUE;
40 | for (int i = 0, l = max.length; i < l; i++) {
41 | result = Math.max(result, max[i] - prices[i]);
42 | }
43 | return result;
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/problems/src/greedy/GasStation.java:
--------------------------------------------------------------------------------
1 | package greedy;
2 |
3 | /**
4 | * Created by gouthamvidyapradhan on 28/06/2017.
5 | * There are N gas stations along a circular route, where the amount of gas at station i is gas[i].
6 | *
7 | * You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations.
8 | *
9 | * Return the starting gas station's index if you can travel around the circuit once, otherwise return -1.
10 | *
11 | * Note:
12 | * The solution is guaranteed to be unique.
13 | *
14 | * Solution: O(N)
15 | * If point B cant be reached from point A then all the intermediate points between A and B cant be the starting
16 | * point. Therefore reset the starting point to the new starting point.
17 | */
18 | public class GasStation {
19 | /**
20 | * Main method
21 | *
22 | * @param args
23 | * @throws Exception
24 | */
25 | public static void main(String[] args) throws Exception {
26 | int[] gas = {10, 20, 30, 10};
27 | int[] cost = {5, 30, 10, 10};
28 | System.out.println(new GasStation().canCompleteCircuit(gas, cost));
29 | }
30 |
31 | public int canCompleteCircuit(int[] gas, int[] cost) {
32 | int debt = 0, sum = 0, start = 0;
33 | for (int i = 0; i < gas.length; i++) {
34 | sum += gas[i] - cost[i];
35 | if (sum < 0) {
36 | debt += sum;
37 | sum = 0;
38 | start = i + 1;
39 | }
40 | }
41 | debt += sum;
42 | return debt >= 0 ? start : -1;
43 | }
44 |
45 | }
46 |
--------------------------------------------------------------------------------
/problems/src/tree/DiameterOfBinaryTree.java:
--------------------------------------------------------------------------------
1 | package tree;
2 |
3 | /**
4 | * Created by gouthamvidyapradhan on 18/10/2017.
5 | *
6 | * Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is
7 | * the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.
8 |
9 | Example:
10 | Given a binary tree
11 | 1
12 | / \
13 | 2 3
14 | / \
15 | 4 5
16 | Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].
17 |
18 | Note: The length of path between two nodes is represented by the number of edges between them.
19 | */
20 | public class DiameterOfBinaryTree {
21 |
22 | public static class TreeNode {
23 | int val;
24 | TreeNode left;
25 | TreeNode right;
26 | TreeNode(int x) { val = x; }
27 | }
28 |
29 | private int max = 0;
30 | /**
31 | * Main method
32 | * @param args
33 | * @throws Exception
34 | */
35 | public static void main(String[] args) throws Exception{
36 | TreeNode root = new TreeNode(5);
37 | root.left = new TreeNode(4);
38 | System.out.println(new DiameterOfBinaryTree().diameterOfBinaryTree(root));
39 | }
40 |
41 | public int diameterOfBinaryTree(TreeNode root) {
42 | dfs(root);
43 | return max;
44 | }
45 |
46 | private int dfs(TreeNode node){
47 | if(node != null){
48 | int left = dfs(node.left);
49 | int right = dfs(node.right);
50 | max = Math.max(max, left + right);
51 | return left > right ? left + 1 : right + 1;
52 | }
53 | return 0;
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/problems/src/tree/SortedArrayToBST.java:
--------------------------------------------------------------------------------
1 | package tree;
2 |
3 | /**
4 | * Created by gouthamvidyapradhan on 25/02/2017.
5 | * Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
6 | */
7 | public class SortedArrayToBST {
8 | public class TreeNode {
9 | int val;
10 | TreeNode left;
11 | TreeNode right;
12 |
13 | TreeNode(int x) {
14 | val = x;
15 | }
16 | }
17 |
18 | /**
19 | * Main method
20 | *
21 | * @param args
22 | * @throws Exception
23 | */
24 | public static void main(String[] args) throws Exception {
25 | int[] A = {1, 2, 3, 4, 5, 6};
26 | new SortedArrayToBST().sortedArrayToBST(A);
27 |
28 | }
29 |
30 | public TreeNode sortedArrayToBST(int[] nums) {
31 | if (nums.length == 0) return null;
32 |
33 | TreeNode root = new SortedArrayToBST().build(0, nums.length - 1, nums);
34 | preorder(root);
35 | return root;
36 | }
37 |
38 | private void preorder(TreeNode node) {
39 | if (node != null) {
40 | preorder(node.left);
41 | System.out.println(node.val);
42 | preorder(node.right);
43 | }
44 | }
45 |
46 | private TreeNode build(int s, int e, int[] nums) {
47 | if (s > e) return null;
48 |
49 | int m = (e - s) / 2;
50 | int node = nums[s + m];
51 | TreeNode root = new TreeNode(node);
52 | if (s == e)
53 | return root;
54 |
55 | root.left = build(s, s + m - 1, nums);
56 | root.right = build(s + m + 1, e, nums);
57 |
58 | return root;
59 | }
60 |
61 | }
62 |
--------------------------------------------------------------------------------
/problems/src/two_pointers/TrappingRainWater.java:
--------------------------------------------------------------------------------
1 | package two_pointers;
2 |
3 | /**
4 | * Created by gouthamvidyapradhan on 08/03/2017.
5 | * 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.
6 | *
7 | * For example,
8 | * Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.
9 | */
10 | public class TrappingRainWater {
11 | /**
12 | * Main method
13 | *
14 | * @param args
15 | * @throws Exception
16 | */
17 | public static void main(String[] args) throws Exception {
18 | int[] height = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1};
19 | System.out.println(new TrappingRainWater().trap(height));
20 | }
21 |
22 | private int trap(int[] height) {
23 | if (height.length == 0) return 0;
24 |
25 | int[] left = new int[height.length];
26 | int[] right = new int[height.length];
27 | int max = 0;
28 | left[0] = 0;
29 | right[height.length - 1] = 0;
30 |
31 | int total = 0;
32 |
33 | for (int i = 1, l = height.length; i < l; i++) {
34 | left[i] = Math.max(max, height[i - 1]);
35 | max = left[i];
36 | }
37 | max = 0;
38 | for (int i = height.length - 2; i >= 0; i--) {
39 | right[i] = Math.max(max, height[i + 1]);
40 | max = right[i];
41 | }
42 | for (int i = 0, l = height.length; i < l; i++) {
43 | int min = Math.min(left[i], right[i]);
44 | if (min > height[i]) {
45 | total += (min - height[i]);
46 | }
47 | }
48 | return total;
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/problems/src/string/OneEditDistance.java:
--------------------------------------------------------------------------------
1 | package string;
2 |
3 | /**
4 | * Created by gouthamvidyapradhan on 09/12/2017.
5 | *
6 | * Given two strings S and T, determine if they are both one edit distance apart.
7 | */
8 | public class OneEditDistance {
9 |
10 | /**
11 | * Main method
12 | * @param args
13 | * @throws Exception
14 | */
15 | public static void main(String[] args) throws Exception{
16 | System.out.println(new OneEditDistance().isOneEditDistance("abxd", "adxb"));
17 | }
18 |
19 | public boolean isOneEditDistance(String s, String t) {
20 | if(Math.abs(s.length() - t.length()) > 1 || s.equals(t)) return false;
21 | if(s.length() > t.length()){
22 | return hasDiffOne(s, t, false);
23 | } else if(t.length() > s.length()){
24 | return hasDiffOne(t, s, false);
25 | } else{
26 | return hasDiffOne(s, t, true);
27 | }
28 | }
29 |
30 | private boolean hasDiffOne(String s, String t, boolean sameLength){
31 | int count = 0, i = 0, j = 0;
32 | for(int l1 = s.length(), l2 = t.length(); i < l1 && j < l2;){
33 | if(s.charAt(i) == t.charAt(j)){
34 | i++; j++;
35 | } else{
36 | if(count > 0) return false;
37 | count++;
38 | if(sameLength){
39 | i++; j++;
40 | } else{
41 | i++;
42 | }
43 | }
44 | }
45 | if(i == j){
46 | return true;
47 | } else{
48 | return (s.charAt(s.length() - 1) == t.charAt(t.length() - 1));
49 | }
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/problems/src/two_pointers/LongestSubstringWitoutRepeats.java:
--------------------------------------------------------------------------------
1 | package two_pointers;
2 |
3 | import java.util.HashMap;
4 | import java.util.HashSet;
5 | import java.util.Map;
6 | import java.util.Set;
7 |
8 | /**
9 | * Created by gouthamvidyapradhan on 09/03/2017.
10 | * Given a string, find the length of the longest substring without repeating characters.
11 | *
12 | * Examples:
13 | *
14 | * Given "abcabcbb", the answer is "abc", which the length is 3.
15 | *
16 | * Given "bbbbb", the answer is "b", with the length of 1.
17 | *
18 | * 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.
19 | */
20 | public class LongestSubstringWitoutRepeats {
21 | Set
10 | * Design the encode and decode methods for the TinyURL service. There is no restriction on how your encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be decoded to the original URL.
11 | */
12 | public class EncodeAndDecodeTinyURL {
13 | private List
10 | * For example,
11 | * [1,2,3] have the following permutations:
12 | * [
13 | * [1,2,3],
14 | * [1,3,2],
15 | * [2,1,3],
16 | * [2,3,1],
17 | * [3,1,2],
18 | * [3,2,1]
19 | * ]
20 | */
21 | public class Permutations {
22 | /**
23 | * Main method
24 | *
25 | * @param args
26 | * @throws Exception
27 | */
28 | public static void main(String[] args) throws Exception {
29 | int[] nums = {1, 2, 3};
30 | List
11 | * Note: The solution set must not contain duplicate subsets.
12 | *
13 | * For example,
14 | * If nums = [1,2,2], a solution is:
15 | *
16 | * [
17 | * [2],
18 | * [1],
19 | * [1,2,2],
20 | * [2,2],
21 | * [1,2],
22 | * []
23 | * ]
24 | */
25 | public class SubsetsII {
26 | /**
27 | * Main method
28 | *
29 | * @param args
30 | * @throws Exception
31 | */
32 | public static void main(String[] args) throws Exception {
33 | int[] n = {1, 2, 3};
34 | List
10 | * click to show follow up.
11 | *
12 | * Follow up:
13 | * Did you use extra space?
14 | * A straight forward solution using O(mn) space is probably a bad idea.
15 | * A simple improvement uses O(m + n) space, but still not the best solution.
16 | * Could you devise a constant space solution?
17 | */
18 | public class SetMatrixZeroes {
19 | /**
20 | * Main method
21 | *
22 | * @param args
23 | * @throws Exception
24 | */
25 | public static void main(String[] args) throws Exception {
26 | int[][] matrix = {{0, 8, 7}, {9, 0, 8}, {9, 9, 0}};
27 |
28 | new SetMatrixZeroes().setZeroes(matrix);
29 | }
30 |
31 | public void setZeroes(int[][] matrix) {
32 | Set
7 | * According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”
8 | *
9 | * _______6______
10 | * / \
11 | * ___2__ ___8__
12 | * / \ / \
13 | * 0 _4 7 9
14 | * / \
15 | * 3 5
16 | * For example, the lowest common ancestor (LCA) of nodes 2 and 8 is 6. Another example is LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.
17 | */
18 |
19 | public class LowestCommonAncestorBST {
20 | class TreeNode {
21 | int val;
22 | TreeNode left;
23 | TreeNode right;
24 |
25 | TreeNode(int x) {
26 | val = x;
27 | }
28 | }
29 |
30 | public static void main(String[] args) throws Exception {
31 |
32 | }
33 |
34 | private TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
35 | if (root == null) return null;
36 |
37 | if (p.val == root.val || q.val == root.val) return root;
38 |
39 | else if ((p.val < root.val && q.val > root.val) || (q.val < root.val && p.val > root.val))
40 | return root;
41 |
42 | else if (p.val < root.val && q.val < root.val)
43 | return lowestCommonAncestor(root.left, p, q);
44 |
45 | else
46 | return lowestCommonAncestor(root.right, p, q);
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/problems/src/math/BulbSwitcherII.java:
--------------------------------------------------------------------------------
1 | package math;
2 |
3 |
4 | /**
5 | * Created by gouthamvidyapradhan on 08/09/2017.
6 | * There is a room with n lights which are turned on initially and 4 buttons on the wall.
7 | * After performing exactly m unknown operations towards buttons, you need to return how many different kinds of status of the n lights could be.
8 | *
9 | * Suppose n lights are labeled as number [1, 2, 3 ..., n], function of these 4 buttons are given below:
10 | *
11 | * Flip all the lights.
12 | * Flip lights with even numbers.
13 | * Flip lights with odd numbers.
14 | * Flip lights with (3k + 1) numbers, k = 0, 1, 2, ...
15 | *
16 | * Example 1:
17 | * Input: n = 1, m = 1.
18 | * Output: 2
19 | * Explanation: Status can be: [on], [off]
20 | *
21 | * Example 2:
22 | * Input: n = 2, m = 1.
23 | * Output: 3
24 | * Explanation: Status can be: [on, off], [off, on], [off, off]
25 | *
26 | * Example 3:
27 | * Input: n = 3, m = 1.
28 | * Output: 4
29 | * Explanation: Status can be: [off, on, off], [on, off, on], [off, off, off], [off, on, on].
30 | *
31 | * Note: n and m both fit in range [0, 1000].
32 | */
33 | public class BulbSwitcherII {
34 |
35 | public static void main(String[] args) throws Exception {
36 | System.out.println(new BulbSwitcherII().flipLights(1, 1000));
37 | }
38 |
39 | public int flipLights(int n, int m) {
40 | if (n == 0 || m == 0) return 1;
41 | if (n == 1 && m >= 1) return 2;
42 | if (n == 2) {
43 | if (m == 1) return 3;
44 | if (m >= 2) return 4;
45 | } else if (n >= 3) {
46 | if (m == 1) return 4;
47 | if (m == 2) return 7;
48 | }
49 | return 8;
50 | }
51 |
52 | }
53 |
--------------------------------------------------------------------------------
/problems/src/math/GlobalAndLocalInversions.java:
--------------------------------------------------------------------------------
1 | package math;
2 |
3 | /**
4 | * Created by gouthamvidyapradhan on 01/02/2018.
5 | *
6 | * We have some permutation A of [0, 1, ..., N - 1], where N is the length of A.
7 |
8 | The number of (global) inversions is the number of i < j with 0 <= i < j < N and A[i] > A[j].
9 |
10 | The number of local inversions is the number of i with 0 <= i < N and A[i] > A[i+1].
11 |
12 | Return true if and only if the number of global inversions is equal to the number of local inversions.
13 |
14 | Example 1:
15 |
16 | Input: A = [1,0,2]
17 | Output: true
18 | Explanation: There is 1 global inversion, and 1 local inversion.
19 | Example 2:
20 |
21 | Input: A = [1,2,0]
22 | Output: false
23 | Explanation: There are 2 global inversions, and 1 local inversion.
24 | Note:
25 |
26 | A will be a permutation of [0, 1, ..., A.length - 1].
27 | A will have length in range [1, 5000].
28 | The time limit for this problem has been reduced.
29 |
30 | Solution: O(N) For every i, Maintain a max value up until (i - 1). If the current element at i < max value return false
31 | */
32 | public class GlobalAndLocalInversions {
33 | /**
34 | * Main method
35 | * @param args
36 | * @throws Exception
37 | */
38 | public static void main(String[] args) throws Exception{
39 |
40 | }
41 |
42 | public boolean isIdealPermutation(int[] A) {
43 | if(A.length == 0 || A.length == 1) return true;
44 | int max = Integer.MIN_VALUE;
45 | for(int i = 1; i < A.length; i ++) {
46 | if(A[i] < max){
47 | return false;
48 | } else{
49 | max = Math.max(max, A[i - 1]);
50 | }
51 | }
52 | return true;
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/problems/src/linked_list/MergeTwoSortedList.java:
--------------------------------------------------------------------------------
1 | package linked_list;
2 |
3 | /**
4 | * Created by gouthamvidyapradhan on 18/03/2017.
5 | * 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.
6 | */
7 | public class MergeTwoSortedList {
8 | public static class ListNode {
9 | int val;
10 | ListNode next;
11 |
12 | ListNode(int x) {
13 | val = x;
14 | next = null;
15 | }
16 | }
17 |
18 | public static void main(String[] args) throws Exception {
19 | ListNode head = new ListNode(0);
20 | ListNode head1 = new ListNode(3);
21 | ListNode head2 = new ListNode(8);
22 |
23 | ListNode head3 = new ListNode(1);
24 | ListNode head4 = new ListNode(2);
25 | ListNode head5 = new ListNode(7);
26 | ListNode head6 = new ListNode(10);
27 |
28 | head.next = head1;
29 | head1.next = head2;
30 |
31 | head3.next = head4;
32 | head4.next = head5;
33 | head5.next = head6;
34 |
35 | ListNode newHead = new MergeTwoSortedList().mergeTwoLists(head, head3);
36 | ListNode link = newHead;
37 | while (link != null) {
38 | System.out.println(link.val);
39 | link = link.next;
40 | }
41 | }
42 |
43 | public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
44 | if (l1 == null) return l2;
45 | else if (l2 == null) return l1;
46 | if (l1.val <= l2.val) {
47 | l1.next = mergeTwoLists(l1.next, l2);
48 | return l1;
49 | } else {
50 | l2.next = mergeTwoLists(l1, l2.next);
51 | return l2;
52 | }
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/problems/src/tree/PreorderToBT.java:
--------------------------------------------------------------------------------
1 | package tree;
2 |
3 | import java.util.HashMap;
4 | import java.util.Map;
5 |
6 | /**
7 | * Created by gouthamvidyapradhan on 25/02/2017.
8 | * Given preorder and inorder traversal of a tree, construct the binary tree.
9 | *
10 | * Note:
11 | * You may assume that duplicates do not exist in the tree.
12 | */
13 | public class PreorderToBT {
14 | public class TreeNode {
15 | int val;
16 | TreeNode left;
17 | TreeNode right;
18 |
19 | TreeNode(int x) {
20 | val = x;
21 | }
22 | }
23 |
24 | Map
7 | * According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”
8 | *
9 | * _______3______
10 | * / \
11 | * ___5__ ___1__
12 | * / \ / \
13 | * 6 _2 0 8
14 | * / \
15 | * 7 4
16 | * For example, the lowest common ancestor (LCA) of nodes 5 and 1 is 3. Another example is LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.
17 | */
18 | public class LCA {
19 | public class TreeNode {
20 | int val;
21 | TreeNode left;
22 | TreeNode right;
23 |
24 | TreeNode(int x) {
25 | val = x;
26 | }
27 | }
28 |
29 | /**
30 | * Main method
31 | *
32 | * @param args
33 | * @throws Exception
34 | */
35 | public static void main(String[] args) throws Exception {
36 |
37 | }
38 |
39 | public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
40 | if (root != null) {
41 | if (root.equals(p) || root.equals(q)) return root;
42 | TreeNode left = lowestCommonAncestor(root.left, p, q);
43 | TreeNode right = lowestCommonAncestor(root.right, p, q);
44 | if (left != null && right != null) return root;
45 | else if (left != null) return left;
46 | else return right;
47 | }
48 | return null;
49 | }
50 |
51 |
52 | }
53 |
--------------------------------------------------------------------------------
/problems/src/bit_manipulation/TotalHammingDistance.java:
--------------------------------------------------------------------------------
1 | package bit_manipulation;
2 |
3 | /**
4 | * Created by gouthamvidyapradhan on 01/12/2017.
5 | * The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
6 |
7 | Now your job is to find the total Hamming distance between all pairs of the given numbers.
8 |
9 | Example:
10 | Input: 4, 14, 2
11 |
12 | Output: 6
13 |
14 | Explanation: In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (just
15 | showing the four bits relevant in this case). So the answer will be:
16 | HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6.
17 | Note:
18 | Elements of the given array are in the range of 0 to 10^9
19 | Length of the array will not exceed 10^4.
20 |
21 | Solution: O(N * 32): Count the number of set bits in each of 32 bit positions and then take the sum of
22 | product of number of set bits x number of un-set bits
23 | */
24 | public class TotalHammingDistance {
25 | /**
26 | * Main method
27 | * @param args
28 | * @throws Exception
29 | */
30 | public static void main(String[] args) throws Exception{
31 | int[] A = {1000000000, 4, 14, 2};
32 | System.out.println(new TotalHammingDistance().totalHammingDistance(A));
33 | }
34 |
35 | public int totalHammingDistance(int[] nums) {
36 | int sum = 0;
37 | for(int i = 0; i < 32; i ++){
38 | int numOfOnes = 0;
39 | int p = (1 << i);
40 | for (int num : nums) {
41 | if ((num & p) > 0) {
42 | numOfOnes++;
43 | }
44 | }
45 | sum += ((nums.length - numOfOnes) * numOfOnes);
46 | }
47 | return sum;
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/problems/src/stack/ValidParentheses.java:
--------------------------------------------------------------------------------
1 | package stack;
2 |
3 | import java.util.HashMap;
4 | import java.util.Map;
5 | import java.util.Stack;
6 |
7 | /**
8 | * Created by gouthamvidyapradhan on 25/02/2017.
9 | * Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
10 | *
11 | * The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.
12 | */
13 | public class ValidParentheses {
14 | public static void main(String[] args) {
15 | System.out.println(hasBalancedBrackets("(h[e"));
16 | }
17 |
18 | private static Map
7 | * For example,
8 | * Given [3,2,1,5,6,4] and k = 2, return 5.
9 | *
10 | * Note:
11 | * You may assume k is always valid, 1 ≤ k ≤ array's length.
12 | */
13 | public class KthLargestElementInAnArray {
14 | /**
15 | * Main method
16 | *
17 | * @param args
18 | * @throws Exception
19 | */
20 | public static void main(String[] args) throws Exception {
21 | int[] nums = {3, 2, 1, 5, 6, 4};
22 |
23 | System.out.println(new KthLargestElementInAnArray().findKthLargest(nums, 6));
24 | }
25 |
26 | private int findKthLargest(int[] nums, int k) {
27 | return solve(nums, 0, nums.length - 1, k);
28 | }
29 |
30 | private int solve(int[] nums, int pIndex, int end, int k) {
31 | int pivot = nums[end];
32 | int temp;
33 | int start = pIndex;
34 | for (int i = pIndex; i < end; i++) {
35 | if (nums[i] <= pivot) {
36 | temp = nums[i];
37 | nums[i] = nums[pIndex];
38 | nums[pIndex] = temp;
39 | pIndex += 1;
40 | }
41 | }
42 | temp = nums[pIndex];
43 | nums[pIndex] = nums[end];
44 | nums[end] = temp;
45 |
46 | int pos = (end - pIndex) + 1;
47 | if (pos == k) return nums[pIndex];
48 | else if (pos > k) {
49 | return solve(nums, pIndex + 1, end, k);
50 | } else {
51 | return solve(nums, start, pIndex - 1, k - pos);
52 | }
53 | }
54 |
55 | }
56 |
--------------------------------------------------------------------------------
/problems/src/tree/BSTtoDoublyLinkedList.java:
--------------------------------------------------------------------------------
1 | package tree;
2 |
3 | /**
4 | * Created by gouthamvidyapradhan on 23/01/2018.
5 | * Convert a BST to a sorted circular doubly-linked list in-place. Think of the left and right pointers as synonymous
6 | * to the previous and next pointers in a doubly-linked list.
7 | *
8 | * Solution: Do a preorder traversal, keep track of previous node at every step and construct the dd-linked list
9 | * in-place.
10 | */
11 | public class BSTtoDoublyLinkedList {
12 |
13 | static class Node {
14 | public int val;
15 | public Node left;
16 | public Node right;
17 |
18 | public Node() {}
19 |
20 | public Node(int _val,Node _left,Node _right) {
21 | val = _val;
22 | left = _left;
23 | right = _right;
24 | }
25 | }
26 |
27 | /**
28 | * Main method
29 | * @param args
30 | * @throws Exception
31 | */
32 | public static void main(String[] args) throws Exception{
33 | Node root = new Node(4, new Node(2, null, null), new Node(5, null, null));
34 | Node result = new BSTtoDoublyLinkedList().treeToDoublyList(root);
35 | //print result
36 | }
37 |
38 | public Node treeToDoublyList(Node root) {
39 | if(root == null) return null;
40 | Node head = new Node();
41 | Node last = preorder(root, head);
42 | last.right = head.right;
43 | head.right.left = last;
44 | return head.right;
45 | }
46 |
47 | Node preorder(Node node, Node prev){
48 | if(node == null) return prev;
49 | else{
50 | Node left = preorder(node.left, prev);
51 | left.right = node;
52 | node.left = left;
53 | return preorder(node.right, node);
54 | }
55 | }
56 |
57 | }
58 |
--------------------------------------------------------------------------------
/problems/src/backtracking/TargetSum.java:
--------------------------------------------------------------------------------
1 | package backtracking;
2 |
3 | /**
4 | * Created by gouthamvidyapradhan on 09/12/2017.
5 | * You are given a list of non-negative integers, a1, a2, ..., an, and a target, S. Now you have 2 symbols + and -.
6 | * For each integer, you should choose one from + and - as its new symbol.
7 |
8 | Find out how many ways to assign symbols to make sum of integers equal to target S.
9 |
10 | Example 1:
11 | Input: nums is [1, 1, 1, 1, 1], S is 3.
12 | Output: 5
13 | Explanation:
14 |
15 | -1+1+1+1+1 = 3
16 | +1-1+1+1+1 = 3
17 | +1+1-1+1+1 = 3
18 | +1+1+1-1+1 = 3
19 | +1+1+1+1-1 = 3
20 |
21 | There are 5 ways to assign symbols to make the sum of nums be target 3.
22 | Note:
23 | The length of the given array is positive and will not exceed 20.
24 | The sum of elements in the given array will not exceed 1000.
25 | Your output answer is guaranteed to be fitted in a 32-bit integer.
26 | *
27 | */
28 | public class TargetSum {
29 |
30 | private static int n;
31 | /**
32 | * Main method
33 | * @param args
34 | * @throws Exception
35 | */
36 | public static void main(String[] args) throws Exception{
37 | int[] A = {1, 1, 1, 1, 1};
38 | n = 0;
39 | new TargetSum().findTargetSumWays(A, 3);
40 | System.out.println(n);
41 | }
42 |
43 | public int findTargetSumWays(int[] nums, int S) {
44 | backtrack(nums, S, 0, 0);
45 | return n;
46 | }
47 |
48 | private void backtrack(int[] nums, int target, int sum, int i){
49 | if(i == nums.length){
50 | if(sum == target){
51 | n++;
52 | }
53 | } else{
54 | backtrack(nums, target, sum + nums[i], i + 1);
55 | backtrack(nums, target, sum - nums[i], i + 1);
56 | }
57 | }
58 |
59 | }
60 |
61 |
--------------------------------------------------------------------------------
/problems/src/tree/FindBottomLeftTreeValue.java:
--------------------------------------------------------------------------------
1 | package tree;
2 |
3 | /**
4 | * Created by gouthamvidyapradhan on 30/08/2017.
5 | * Given a binary tree, find the leftmost value in the last row of the tree.
6 | *
7 | * Example 1:
8 | * Input:
9 | *
10 | * 2
11 | * / \
12 | * 1 3
13 | *
14 | * Output:
15 | * 1
16 | * Example 2:
17 | * Input:
18 | *
19 | * 1
20 | * / \
21 | * 2 3
22 | * / / \
23 | * 4 5 6
24 | * /
25 | * 7
26 | *
27 | * Output:
28 | * 7
29 | * Note: You may assume the tree (i.e., the given root node) is not NULL.
30 | */
31 | public class FindBottomLeftTreeValue {
32 | private int max = 0, result;
33 |
34 | public static class TreeNode {
35 | int val;
36 | TreeNode left;
37 | TreeNode right;
38 |
39 | TreeNode(int x) {
40 | val = x;
41 | }
42 | }
43 |
44 | public static void main(String[] args) throws Exception {
45 | TreeNode root = new TreeNode(1);
46 | root.left = new TreeNode(2);
47 | root.left.left = new TreeNode(4);
48 | root.right = new TreeNode(3);
49 | root.right.left = new TreeNode(5);
50 | root.right.left.left = new TreeNode(7);
51 | root.right.right = new TreeNode(6);
52 | System.out.println(new FindBottomLeftTreeValue().findBottomLeftValue(root));
53 | }
54 |
55 | public int findBottomLeftValue(TreeNode root) {
56 | preorder(root, 1);
57 | return result;
58 | }
59 |
60 | private void preorder(TreeNode node, int level) {
61 | if (node != null) {
62 | if (level > max) {
63 | result = node.val;
64 | max = level;
65 | }
66 | preorder(node.left, level + 1);
67 | preorder(node.right, level + 1);
68 | }
69 | }
70 | }
71 |
--------------------------------------------------------------------------------
/problems/src/depth_first_search/MovieRecommend.java:
--------------------------------------------------------------------------------
1 | package depth_first_search;
2 |
3 | import java.util.*;
4 |
5 | /**
6 | * Created by gouthamvidyapradhan on 25/02/2017.
7 | * Accepted
8 | */
9 | public class MovieRecommend {
10 | Set
7 | * Example 1:
8 | * Input: "abab"
9 | *
10 | * Output: True
11 | *
12 | * Explanation: It's the substring "ab" twice.
13 | * Example 2:
14 | * Input: "aba"
15 | *
16 | * Output: False
17 | * Example 3:
18 | * Input: "abcabcabcabc"
19 | *
20 | * Output: True
21 | *
22 | * Explanation: It's the substring "abc" four times. (And the substring "abcabc" twice.)
23 | */
24 | public class RepeatedSubstringPattern {
25 | /**
26 | * Main method
27 | *
28 | * @param args
29 | * @throws Exception
30 | */
31 | public static void main(String[] args) throws Exception {
32 | System.out.println(new RepeatedSubstringPattern().repeatedSubstringPattern("a"));
33 | }
34 |
35 | public boolean repeatedSubstringPattern(String s) {
36 | boolean found;
37 | for (int i = 1, l = s.length(); i < l; i++) {
38 | found = true;
39 | String subI = s.substring(0, i);
40 | int j = i;
41 | if (j >= l) return false;
42 | while (j < l) {
43 | if ((j + i) >= l + 1)
44 | return false;
45 | String subJ = s.substring(j, j + i);
46 | if (!subI.equals(subJ)) {
47 | found = false;
48 | break;
49 | }
50 | j += i;
51 | }
52 | if (found) return true;
53 | }
54 | return false;
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/problems/src/dynamic_programming/CombinationSumIV.java:
--------------------------------------------------------------------------------
1 | package dynamic_programming;
2 |
3 | import java.util.Arrays;
4 |
5 | /**
6 | * Created by gouthamvidyapradhan on 17/12/2017.
7 | * Given an integer array with all positive numbers and no duplicates, find the number of possible combinations that
8 | * add up to a positive integer target.
9 |
10 | Example:
11 |
12 | nums = [1, 2, 3]
13 | target = 4
14 |
15 | The possible combination ways are:
16 | (1, 1, 1, 1)
17 | (1, 1, 2)
18 | (1, 2, 1)
19 | (1, 3)
20 | (2, 1, 1)
21 | (2, 2)
22 | (3, 1)
23 |
24 | Note that different sequences are counted as different combinations.
25 |
26 | Therefore the output is 7.
27 | Follow up:
28 | What if negative numbers are allowed in the given array?
29 | How does it change the problem?
30 | What limitation we need to add to the question to allow negative numbers?
31 |
32 | Solution: Backtrack and dp
33 | */
34 | public class CombinationSumIV {
35 |
36 | /**
37 | * Main method
38 | * @param args
39 | * @throws Exception
40 | */
41 | public static void main(String[] args) throws Exception{
42 | int[] A = {1, 2, 3};
43 | System.out.println(new CombinationSumIV().combinationSum4(A, 4));
44 | }
45 |
46 | public int combinationSum4(int[] nums, int target) {
47 | int[] dp = new int[target + 1];
48 | Arrays.fill(dp, -1);
49 | dp[0] = 1;
50 | return backtrack(nums, dp, target);
51 | }
52 |
53 | private int backtrack(int[] nums, int[] dp, int sum){
54 | int total = 0;
55 | if(sum < 0) return 0;
56 | if(dp[sum] != -1) return dp[sum];
57 | else{
58 | for (int num : nums) {
59 | total += backtrack(nums, dp, sum - num);
60 | }
61 | }
62 | dp[sum] = total;
63 | return dp[sum];
64 | }
65 |
66 | }
67 |
--------------------------------------------------------------------------------
/problems/src/string/ReverseWordsInAString.java:
--------------------------------------------------------------------------------
1 | package string;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 | import java.util.StringTokenizer;
6 |
7 | /**
8 | * Created by gouthamvidyapradhan on 04/07/2017.
9 | * Given an input string, reverse the string word by word.
10 | *
11 | * For example,
12 | * Given s = "the sky is blue",
13 | * return "blue is sky the".
14 | *
15 | * Clarification:
16 | * What constitutes a word?
17 | * A sequence of non-space characters constitutes a word.
18 | * Could the input string contain leading or trailing spaces?
19 | * Yes. However, your reversed string should not contain leading or trailing spaces.
20 | * How about multiple spaces between two words?
21 | * Reduce them to a single space in the reversed string.
22 | */
23 | public class ReverseWordsInAString {
24 | public static void main(String[] args) throws Exception {
25 | System.out.println(new ReverseWordsInAString().reverseWords(" the sky is blue"));
26 | }
27 |
28 | public String reverseWords(String s) {
29 | if (s == null || s.isEmpty()) return "";
30 | StringBuilder sb = new StringBuilder(s.trim());
31 | String reverse = sb.reverse().toString();
32 | StringTokenizer st = new StringTokenizer(reverse, " ");
33 | List
7 | * Example 1:
8 | *
9 | * 11110
10 | * 11010
11 | * 11000
12 | * 00000
13 | * Answer: 1
14 | *
15 | * Example 2:
16 | *
17 | * 11000
18 | * 11000
19 | * 00100
20 | * 00011
21 | * Answer: 3
22 | */
23 | public class NumberOfIslands {
24 | int[] R = {0, 0, 1, -1};
25 | int[] C = {1, -1, 0, 0};
26 | private static int M, N;
27 | private static char temp[][];
28 |
29 | public int numIslands(char[][] grid) {
30 | M = grid.length;
31 | if (M == 0) return 0;
32 | N = grid[0].length;
33 | temp = new char[M][N];
34 | int count = 0;
35 |
36 | for (int i = 0; i < M; i++) {
37 | System.arraycopy(grid[i], 0, temp[i], 0, N);
38 | }
39 |
40 | for (int i = 0; i < M; i++) {
41 | for (int j = 0; j < N; j++) {
42 | if (temp[i][j] == '1') {
43 | ++count;
44 | dfs(i, j);
45 | }
46 | }
47 | }
48 |
49 | return count;
50 | }
51 |
52 | private void dfs(int r, int c) {
53 | temp[r][c] = '0';
54 | for (int i = 0; i < 4; i++) {
55 | int newR = r + R[i];
56 | int newC = c + C[i];
57 | if (newR >= 0 && newC >= 0 && newR < M && newC < N) {
58 | if (temp[newR][newC] != '0') //not visited
59 | {
60 | dfs(newR, newC);
61 | }
62 | }
63 | }
64 | }
65 | }
66 |
--------------------------------------------------------------------------------
/problems/src/reservoir_sampling/RandomPickIndex.java:
--------------------------------------------------------------------------------
1 | package reservoir_sampling;
2 |
3 | import java.util.Random;
4 |
5 | /**
6 | * Created by gouthamvidyapradhan on 10/12/2017.
7 | * Given an array of integers with possible duplicates, randomly output the index of a given target number. You can
8 | * assume that the given target number must exist in the array.
9 |
10 | Note:
11 | The array size can be very large. Solution that uses too much extra space will not pass the judge.
12 |
13 | Example:
14 |
15 | int[] nums = new int[] {1,2,3,3,3};
16 | Solution solution = new Solution(nums);
17 |
18 | // pick(3) should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning.
19 | solution.pick(3);
20 |
21 | // pick(1) should return 0. Since in the array only nums[0] is equal to 1.
22 | solution.pick(1);
23 |
24 | */
25 | public class RandomPickIndex {
26 |
27 | private int[] nums;
28 | /**
29 | * Main method
30 | * @param args
31 | * @throws Exception
32 | */
33 | public static void main(String[] args) throws Exception{
34 | int[] A = {1,2,3,3,3};
35 | System.out.println(new RandomPickIndex(A).pick(1));
36 | }
37 |
38 | public RandomPickIndex(int[] nums) {
39 | this.nums = nums;
40 | }
41 |
42 | public int pick(int target) {
43 | int count = 0;
44 | for (int num : nums) {
45 | if (num == target) {
46 | count++;
47 | }
48 | }
49 | Random random = new Random();
50 | int nPick = 1 + random.nextInt(count);
51 | count = 0;
52 | for(int i = 0; i < nums.length; i ++){
53 | if(nums[i] == target){
54 | if(++count == nPick){
55 | return i;
56 | }
57 | }
58 | }
59 | return 0; //this is impossible
60 | }
61 |
62 | }
63 |
--------------------------------------------------------------------------------
/problems/src/tree/ZigZagTraversal.java:
--------------------------------------------------------------------------------
1 | package tree;
2 |
3 | import java.util.ArrayList;
4 | import java.util.LinkedList;
5 | import java.util.List;
6 |
7 | /**
8 | * Created by pradhang on 7/11/2017.
9 | * Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).
10 | *
11 | * For example:
12 | * Given binary tree [3,9,20,null,null,15,7],
13 | * 3
14 | * / \
15 | * 9 20
16 | * / \
17 | * 15 7
18 | * return its zigzag level order traversal as:
19 | * [
20 | * [3],
21 | * [20,9],
22 | * [15,7]
23 | * ]
24 | */
25 | public class ZigZagTraversal {
26 |
27 | public class TreeNode {
28 | int val;
29 | TreeNode left;
30 | TreeNode right;
31 |
32 | TreeNode(int x) {
33 | val = x;
34 | }
35 | }
36 |
37 | public static void main(String[] args) throws Exception {
38 |
39 | }
40 |
41 | public List
10 | * Given an absolute path for a file (Unix-style), simplify it.
11 | *
12 | * For example,
13 | * path = "/home/", => "/home"
14 | * path = "/a/./b/../../c/", => "/c"
15 | *
16 | * Corner Cases:
17 | * Did you consider the case where path = "/../"?
18 | * In this case, you should return "/".
19 | * Another corner case is the path might contain multiple slashes '/' together, such as "/home//foo/".
20 | * In this case, you should ignore redundant slashes and return "/home/foo".
21 | */
22 | public class SimplifyPath {
23 | /**
24 | * Main method
25 | *
26 | * @param args
27 | * @throws Exception
28 | */
29 | public static void main(String[] args) throws Exception {
30 | System.out.println(new SimplifyPath().simplifyPath("/home/"));
31 | }
32 |
33 | public String simplifyPath(String path) {
34 | if (path == null || path.isEmpty()) return "/";
35 | StringTokenizer st = new StringTokenizer(path, "/");
36 | Deque
7 | * Assume Bk to be an array obtained by rotating the array A k positions clock-wise, we define a "rotation function" F on A as follow:
8 | *
9 | * F(k) = 0 * Bk[0] + 1 * Bk[1] + ... + (n-1) * Bk[n-1].
10 | *
11 | * Calculate the maximum value of F(0), F(1), ..., F(n-1).
12 | *
13 | * Note:
14 | * n is guaranteed to be less than 105.
15 | *
16 | * Example:
17 | *
18 | * A = [4, 3, 2, 6]
19 | *
20 | * F(0) = (0 * 4) + (1 * 3) + (2 * 2) + (3 * 6) = 0 + 3 + 4 + 18 = 25
21 | * F(1) = (0 * 6) + (1 * 4) + (2 * 3) + (3 * 2) = 0 + 4 + 6 + 6 = 16
22 | * F(2) = (0 * 2) + (1 * 6) + (2 * 4) + (3 * 3) = 0 + 6 + 8 + 9 = 23
23 | * F(3) = (0 * 3) + (1 * 2) + (2 * 6) + (3 * 4) = 0 + 2 + 12 + 12 = 26
24 | *
25 | * So the maximum value of F(0), F(1), F(2), F(3) is F(3) = 26.
26 | */
27 | public class RotateFunction {
28 | /**
29 | * Main method
30 | *
31 | * @param args
32 | * @throws Exception
33 | */
34 | public static void main(String[] args) throws Exception {
35 | int[] a = {4, 3, 2, 6};
36 | System.out.println(new RotateFunction().maxRotateFunction(a));
37 | }
38 |
39 | public int maxRotateFunction(int[] A) {
40 | if (A.length == 0 || A.length == 1) return 0;
41 | int max = Integer.MIN_VALUE;
42 | int l = A.length;
43 | int sum = 0, prodSum = 0;
44 | for (int i = 0; i < l; i++) {
45 | prodSum += (A[i] * i);
46 | sum += A[i];
47 | }
48 | max = Math.max(max, prodSum);
49 | for (int i = 0; i < l - 1; i++) {
50 | prodSum = (prodSum - sum + A[i] + ((l - 1) * A[i]));
51 | max = Math.max(max, prodSum);
52 | }
53 | return max;
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/problems/src/string/PermutationInString.java:
--------------------------------------------------------------------------------
1 | package string;
2 |
3 | /**
4 | * Created by gouthamvidyapradhan on 18/09/2017.
5 | * Given two strings s1 and s2, write a function to return true if s2 contains the permutation of s1. In other
6 | * words, one of the first string's permutations is the substring of the second string.
7 |
8 | Example 1:
9 | Input:s1 = "ab" s2 = "eidbaooo"
10 | Output:True
11 | Explanation: s2 contains one permutation of s1 ("ba").
12 |
13 | Example 2:
14 | Input:s1= "ab" s2 = "eidboaoo"
15 | Output: False
16 | Note:
17 | The input strings only contain lower case letters.
18 | The length of both given strings is in range [1, 10,000].
19 |
20 | */
21 | public class PermutationInString {
22 | private int[] S1 = new int[256];
23 | private int[] S2 = new int[256];
24 |
25 | /**
26 | * Main method
27 | * @param args
28 | * @throws Exception
29 | */
30 | public static void main(String[] args) throws Exception{
31 | System.out.println(new PermutationInString().checkInclusion("ab", "eidboaoo"));
32 | }
33 |
34 | public boolean checkInclusion(String s1, String s2) {
35 | if(s2.length() < s1.length()) return false;
36 | for(int i = 0, l = s1.length(); i < l; i ++){
37 | S1[s1.charAt(i)] ++;
38 | S2[s2.charAt(i)] ++;
39 | }
40 | if(isEqual()) return true;
41 | for(int i = 1, j = s1.length(), l = s2.length(); j < l; i++, j++){
42 | S2[s2.charAt(i - 1)] --;
43 | S2[s2.charAt(j)] ++;
44 | if(isEqual()) return true;
45 | }
46 | return false;
47 | }
48 |
49 | private boolean isEqual(){
50 | boolean equal = true;
51 | for(int i = 0; i < 256; i ++){
52 | if(S1[i] != S2[i]){
53 | equal = false;
54 | break;
55 | }
56 | }
57 | return equal;
58 | }
59 |
60 | }
61 |
--------------------------------------------------------------------------------
/problems/src/two_pointers/MinimumSizeSubarraySum.java:
--------------------------------------------------------------------------------
1 | package two_pointers;
2 |
3 | /**
4 | * Created by gouthamvidyapradhan on 03/12/2017.
5 | *
6 | * Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous
7 | * subarray of which the sum ≥ s. If there isn't one, return 0 instead.
8 |
9 | For example, given the array [2,3,1,2,4,3] and s = 7,
10 | the subarray [4,3] has the minimal length under the problem constraint.
11 |
12 | click to show more practice.
13 |
14 | Credits:
15 | Special thanks to @Freezen for adding this problem and creating all test cases.
16 |
17 | Solution: O(n) solution. Solve using sliding window sub-array sum using two pointers.
18 | */
19 | public class MinimumSizeSubarraySum {
20 | /**
21 | * Main method
22 | * @param args
23 | * @throws Exception
24 | */
25 | public static void main(String[] args) throws Exception{
26 | int[] nums = {2,3,1,2,4,3};
27 | System.out.println(new MinimumSizeSubarraySum().minSubArrayLen(7, nums));
28 | }
29 |
30 | public int minSubArrayLen(int s, int[] nums) {
31 | int sum = 0, count = 0, min = Integer.MAX_VALUE;
32 | for(int i = 0, j = 0; j < nums.length;){
33 | if(nums[j] >= s){
34 | return 1;
35 | } else{
36 | sum += nums[j];
37 | count ++;
38 | if(sum >= s){
39 | min = Math.min(min, count);
40 | while(j > i){
41 | sum -= nums[i];
42 | count --;
43 | i ++;
44 | if(sum < s) break;
45 | min = Math.min(min, count);
46 | }
47 | }
48 | }
49 | j ++;
50 | }
51 | if(min == Integer.MAX_VALUE){
52 | return 0;
53 | }
54 | return min;
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/problems/src/backtracking/PalindromePartitioning.java:
--------------------------------------------------------------------------------
1 | package backtracking;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | /**
7 | * Created by pradhang on 3/15/2017.
8 | * Given a string s, partition s such that every substring of the partition is a palindrome.
9 | *
10 | * Return all possible palindrome partitioning of s.
11 | *
12 | * For example, given s = "aab",
13 | * Return
14 | *
15 | * [
16 | * ["aa","b"],
17 | * ["a","a","b"]
18 | * ]
19 | */
20 | public class PalindromePartitioning {
21 | /**
22 | * Main method
23 | *
24 | * @param args
25 | * @throws Exception
26 | */
27 | public static void main(String[] args) throws Exception {
28 | List
7 | * Example 1:
8 | * Given tree s:
9 | *
10 | * 3
11 | * / \
12 | * 4 5
13 | * / \
14 | * 1 2
15 | * Given tree t:
16 | * 4
17 | * / \
18 | * 1 2
19 | * Return true, because t has the same structure and node values with a subtree of s.
20 | * Example 2:
21 | * Given tree s:
22 | *
23 | * 3
24 | * / \
25 | * 4 5
26 | * / \
27 | * 1 2
28 | * /
29 | * 0
30 | * Given tree t:
31 | * 4
32 | * / \
33 | * 1 2
34 | * Return false.
35 | */
36 | public class SubtreeOfAnotherTree {
37 | public class TreeNode {
38 | int val;
39 | TreeNode left;
40 | TreeNode right;
41 |
42 | TreeNode(int x) {
43 | val = x;
44 | }
45 | }
46 |
47 | public static void main(String[] args) throws Exception {
48 | }
49 |
50 | public boolean isSubtree(TreeNode s, TreeNode t) {
51 | if (s != null) {
52 | if (s.val == t.val) {
53 | if (equal(s, t))
54 | return true;
55 | else return (isSubtree(s.left, t) || isSubtree(s.right, t));
56 | } else return (isSubtree(s.left, t) || isSubtree(s.right, t));
57 | }
58 | return false;
59 | }
60 |
61 | private boolean equal(TreeNode s, TreeNode t) {
62 | if (s == null && t == null)
63 | return true;
64 | else if (s == null || t == null)
65 | return false;
66 | else if (s.val != t.val) return false;
67 | else return equal(s.left, t.left) && equal(s.right, t.right);
68 | }
69 |
70 | }
71 |
--------------------------------------------------------------------------------
/problems/src/divide_and_conquer/SearchA2DMatrix.java:
--------------------------------------------------------------------------------
1 | package divide_and_conquer;
2 |
3 | /**
4 | * Created by gouthamvidyapradhan on 09/03/2017.
5 | * Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
6 | *
7 | * Integers in each row are sorted in ascending from left to right.
8 | * Integers in each column are sorted in ascending from top to bottom.
9 | * For example,
10 | *
11 | * Consider the following matrix:
12 | *
13 | * [
14 | * [1, 4, 7, 11, 15],
15 | * [2, 5, 8, 12, 19],
16 | * [3, 6, 9, 16, 22],
17 | * [10, 13, 14, 17, 24],
18 | * [18, 21, 23, 26, 30]
19 | * ]
20 | * Given target = 5, return true.
21 | *
22 | * Given target = 20, return false.
23 | */
24 | public class SearchA2DMatrix {
25 | /**
26 | * Main method
27 | *
28 | * @param args
29 | * @throws Exception
30 | */
31 | public static void main(String[] args) throws Exception {
32 | int[][] matrix =
33 | {
34 | {1, 3, 5, 7, 9}, //1, 3, 5, 7, 9
35 | {2, 4, 6, 8, 10}, //2, 4, 6, 8, 10
36 | {11, 13, 15, 17, 19}, //11, 15, 17, 18, 19
37 | {12, 14, 16, 18, 20}, //13, 20, 21, 22, 23
38 | {21, 22, 23, 24, 25} //14, 25, 26, 27, 28
39 | };
40 |
41 | System.out.println(new SearchA2DMatrix().searchMatrix(matrix, 11));
42 | }
43 |
44 | private boolean searchMatrix(int[][] matrix, int target) {
45 | if (matrix.length == 0) return false;
46 | int M = matrix.length;
47 | int N = matrix[0].length;
48 | int r = 0, c = N - 1;
49 | while (r < M && c >= 0) {
50 | if (matrix[r][c] == target) return true;
51 | else if (target < matrix[r][c]) --c;
52 | else if (target > matrix[r][c]) r++;
53 | }
54 | return false;
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/problems/src/dynamic_programming/LongestPaliandromicSubstring.java:
--------------------------------------------------------------------------------
1 | package dynamic_programming;
2 |
3 | /**
4 | * Created by gouthamvidyapradhan on 24/02/2017.
5 | * Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
6 | *
7 | * Example:
8 | *
9 | * Input: "babad"
10 | *
11 | * Output: "bab"
12 | *
13 | * Note: "aba" is also a valid answer.
14 | * Example:
15 | *
16 | * Input: "cbbd"
17 | *
18 | * Output: "bb"
19 | */
20 | public class LongestPaliandromicSubstring {
21 | /**
22 | * Main method
23 | *
24 | * @param args
25 | * @throws Exception
26 | */
27 | public static void main(String[] args) throws Exception {
28 | System.out.println(new LongestPaliandromicSubstring().longestPalindrome("forgeeksskeegfor"));
29 | }
30 |
31 | public String longestPalindrome(String s) {
32 | int l = s.length();
33 | int startIndex = 0;
34 | int maxLen = 1;
35 | boolean[][] A = new boolean[l][l];
36 | for (int i = 0, j = 0; i < l; i++, j++)
37 | A[i][j] = true;
38 |
39 | for (int i = 0, j = i + 1; j < l; i++, j++) {
40 | if (s.charAt(i) == s.charAt(j)) {
41 | A[i][j] = true;
42 | startIndex = i;
43 | maxLen = 2;
44 | }
45 | }
46 |
47 | for (int k = 3; k <= l; k++) {
48 | for (int i = 0, j = k - 1; j < l; i++, j++) {
49 | if (s.charAt(i) == s.charAt(j)) {
50 | A[i][j] = A[i + 1][j - 1];
51 | if (A[i][j]) {
52 | if (k > maxLen) {
53 | startIndex = i;
54 | maxLen = k;
55 | }
56 | }
57 | }
58 | }
59 | }
60 |
61 | return s.substring(startIndex, startIndex + maxLen);
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/problems/src/tree/BinaryTreeInorderTraversal.java:
--------------------------------------------------------------------------------
1 | package tree;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 | import java.util.Stack;
6 |
7 | /**
8 | * Created by gouthamvidyapradhan on 06/08/2017.
9 | * Given a binary tree, return the inorder traversal of its nodes' values.
10 | *
11 | * For example:
12 | * Given binary tree [1,null,2,3],
13 | * 1
14 | * \
15 | * 2
16 | * /
17 | * 3
18 | * return [1,3,2].
19 | *
20 | * Note: Recursive solution is trivial, could you do it iteratively?
21 | */
22 | public class BinaryTreeInorderTraversal {
23 | public static class TreeNode {
24 | int val;
25 | TreeNode left;
26 | TreeNode right;
27 |
28 | TreeNode(int x) {
29 | val = x;
30 | }
31 | }
32 |
33 | public static void main(String[] args) throws Exception {
34 | TreeNode root = new TreeNode(3);
35 | root.left = new TreeNode(4);
36 | root.left.left = new TreeNode(5);
37 | root.left.right = new TreeNode(6);
38 | root.left.left.left = new TreeNode(9);
39 | root.left.left.right = new TreeNode(10);
40 | root.right = new TreeNode(2);
41 | root.right.left = new TreeNode(7);
42 | root.right.right = new TreeNode(8);
43 | List
7 | * Note:
8 | * Given target value is a floating point.
9 | * You are guaranteed to have only one unique value in the BST that is closest to the target.
10 | *
11 | * Solution: Simple dfs recursive algorithm to find the closest match.
12 | * Worst case time complexity is O(h) where h is height of the tree
13 | */
14 | public class ClosestBinarySearchTreeValue {
15 | /**
16 | * TreeNode
17 | */
18 | public static class TreeNode {
19 | int val;
20 | TreeNode left;
21 | TreeNode right;
22 |
23 | TreeNode(int x) {
24 | val = x;
25 | }
26 | }
27 |
28 | private double absDiff = Double.MAX_VALUE;
29 | private int closest;
30 |
31 | /**
32 | * Main method
33 | *
34 | * @param args
35 | * @throws Exception
36 | */
37 | public static void main(String[] args) throws Exception {
38 | TreeNode root = new TreeNode(10);
39 | root.left = new TreeNode(9);
40 | root.left.left = new TreeNode(8);
41 | System.out.println(new ClosestBinarySearchTreeValue().closestValue(root, 7.63354D));
42 | }
43 |
44 | /**
45 | * Find closest
46 | *
47 | * @param root Root node
48 | * @param target double target
49 | * @return closest value
50 | */
51 | public int closestValue(TreeNode root, double target) {
52 | if (root == null) return closest;
53 | if (Math.abs(target - root.val) < absDiff) {
54 | absDiff = Math.abs(target - root.val);
55 | closest = root.val;
56 | }
57 | if (root.val > target)
58 | return closestValue(root.left, target);
59 | else return closestValue(root.right, target);
60 | }
61 |
62 | }
63 |
--------------------------------------------------------------------------------
/problems/src/dynamic_programming/BestTimeToBuyAndSellStockIII.java:
--------------------------------------------------------------------------------
1 | package dynamic_programming;
2 |
3 | /**
4 | * Created by gouthamvidyapradhan on 15/02/2018.
5 | * Say you have an array for which the ith element is the price of a given stock on day i.
6 |
7 | Design an algorithm to find the maximum profit. You may complete at most two transactions.
8 |
9 | Note:
10 | You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
11 |
12 | Solution: O(n): In the first iteration calculate the max profit that can be made by one buy and sell by iterating from
13 | right to left and saving this in a dp array and maintaining a max value.
14 | In the second iteration starting from left to right maintain a min value and calculate the max profit that can be
15 | made by one buy and sell by taking the difference of current with min and calculate the total profit of two
16 | transactions by summing up the current profit made with the profit in dp array.
17 | */
18 | public class BestTimeToBuyAndSellStockIII {
19 |
20 | /**
21 | * Main method
22 | * @param args
23 | */
24 | public static void main(String[] args) throws Exception{
25 | int[] A = {10, 9, 8, 7};
26 | System.out.println(new BestTimeToBuyAndSellStockIII().maxProfit(A));
27 | }
28 |
29 | public int maxProfit(int[] prices) {
30 | if(prices.length == 0 || prices.length == 1) return 0;
31 | int[] dp = new int[prices.length];
32 | int min = prices[0];
33 | int max = prices[prices.length - 1];
34 | for(int i = prices.length - 2; i >= 0; i--){
35 | dp[i] = Math.max(max - prices[i], dp[i + 1]);
36 | max = Math.max(max, prices[i]);
37 | }
38 | max = Integer.MIN_VALUE;
39 | for(int i = 0; i < prices.length; i ++){
40 | max = Math.max(max, prices[i] - min + dp[i]);
41 | min = Math.min(min, prices[i]);
42 | }
43 | return max;
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/problems/src/dynamic_programming/SplitArrayLargestSum.java:
--------------------------------------------------------------------------------
1 | package dynamic_programming;
2 |
3 | /**
4 | * Created by gouthamvidyapradhan on 24/12/2017.
5 | * Given an array which consists of non-negative integers and an integer m, you can split the array into m non-empty
6 | * continuous subarrays. Write an algorithm to minimize the largest sum among these m subarrays.
7 |
8 | Note:
9 | If n is the length of array, assume the following constraints are satisfied:
10 |
11 | 1 ≤ n ≤ 1000
12 | 1 ≤ m ≤ min(50, n)
13 | Examples:
14 |
15 | Input:
16 | nums = [7,2,5,10,8]
17 | m = 2
18 |
19 | Output:
20 | 18
21 |
22 | Explanation:
23 | There are four ways to split nums into two subarrays.
24 | The best way is to split it into [7,2,5] and [10,8],
25 | where the largest sum among the two subarrays is only 18.
26 |
27 | Solution O(n ^ 2 * k)
28 | Build a bottom up min-max dp table for each sub-array ranging from n -> 0
29 | */
30 | public class SplitArrayLargestSum {
31 |
32 | /**
33 | * Main method
34 | * @param args
35 | * @throws Exception
36 | */
37 | public static void main(String[] args) throws Exception{
38 | int[] A = {7,2,5,10,8};
39 | System.out.println(new SplitArrayLargestSum().splitArray(A, 2));
40 | }
41 |
42 | public int splitArray(int[] nums, int m) {
43 | int[][] dp = new int[m][nums.length];
44 | for(int i = nums.length - 1; i >= 0; i --){
45 | int sum = 0;
46 | for(int j = i; j < nums.length; j ++){
47 | sum += nums[j];
48 | if(j + 1 >= nums.length) break;
49 | for(int k = 0; k < m - 1; k++){
50 | dp[k + 1][i] = (dp[k + 1][i] == 0) ? Integer.MAX_VALUE : dp[k + 1][i];
51 | int temp = Math.max(sum, dp[k][j + 1]);
52 | dp[k + 1][i] = Math.min(dp[k + 1][i], temp);
53 | }
54 | }
55 | dp[0][i] = sum;
56 | }
57 | return dp[m - 1][0];
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/problems/src/linked_list/SwapNodesInPairs.java:
--------------------------------------------------------------------------------
1 | package linked_list;
2 |
3 | /**
4 | * Created by gouthamvidyapradhan on 13/08/2017.
5 | * Given a linked list, swap every two adjacent nodes and return its head.
6 | *
7 | * For example,
8 | * Given 1->2->3->4, you should return the list as 2->1->4->3.
9 | *
10 | * Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
11 | */
12 | public class SwapNodesInPairs {
13 |
14 | public static class ListNode {
15 | int val;
16 | ListNode next;
17 |
18 | ListNode(int x) {
19 | val = x;
20 | }
21 | }
22 |
23 | public static void main(String[] args) throws Exception {
24 | ListNode node = new ListNode(1);
25 | node.next = new ListNode(2);
26 | node.next.next = new ListNode(3);
27 | node.next.next.next = new ListNode(4);
28 | node.next.next.next.next = new ListNode(5);
29 | node.next.next.next.next.next = new ListNode(6);
30 | ListNode head = new SwapNodesInPairs().swapPairs(node);
31 | while (head != null) {
32 | System.out.println(head.val);
33 | head = head.next;
34 | }
35 | }
36 |
37 | public ListNode swapPairs(ListNode head) {
38 | if (head == null || head.next == null)
39 | return head;
40 | ListNode newHead = head.next;
41 | ListNode curr = head.next;
42 | ListNode prev = head;
43 | ListNode prevPrev = new ListNode(-1); //dummy node
44 | while (curr != null) {
45 | prev.next = curr.next;
46 | curr.next = prev;
47 | prevPrev.next = curr;
48 | if (prev.next != null) {
49 | curr = prev.next.next;
50 | prev = prev.next;
51 | prevPrev = prevPrev.next.next;
52 | } else {
53 | curr = null;
54 | }
55 | }
56 | return newHead;
57 | }
58 |
59 | }
60 |
--------------------------------------------------------------------------------
/problems/src/backtracking/LetterPhoneNumber.java:
--------------------------------------------------------------------------------
1 | package backtracking;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | /**
7 | * Created by gouthamvidyapradhan on 09/03/2017.
8 | * Given a digit string, return all possible letter combinations that the number could represent.
9 | *
10 | * A mapping of digit to letters (just like on the telephone buttons) is given below.
11 | * 1 2(abc) 3(def)
12 | * 4(ghi) 5(jkl) 6(mno)
13 | * 7(pqrs) 8(tuv) 9(wxyz)
14 | *
15 | *
16 | * Input:Digit string "23"
17 | * Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
18 | * Note:
19 | * Although the above answer is in lexicographical order, your answer could be in any order you want.
20 | */
21 | public class LetterPhoneNumber {
22 | private String[] NUMBER_ALPHA = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
23 |
24 | /**
25 | * Main method
26 | *
27 | * @param args
28 | * @throws Exception
29 | */
30 | public static void main(String[] args) throws Exception {
31 | List
9 | * You may assume that each input would have exactly one solution, and you may not use the same element twice.
10 | *
11 | * Example:
12 | * Given nums = [2, 7, 11, 15], target = 9,
13 | *
14 | * Because nums[0] + nums[1] = 2 + 7 = 9,
15 | * return [0, 1].
16 | */
17 | public class TwoSum {
18 | HashMap
7 | * Example 1:
8 | * Input: [3, 2, 1]
9 | *
10 | * Output: 1
11 | *
12 | * Explanation: The third maximum is 1.
13 | * Example 2:
14 | * Input: [1, 2]
15 | *
16 | * Output: 2
17 | *
18 | * Explanation: The third maximum does not exist, so the maximum (2) is returned instead.
19 | * Example 3:
20 | * Input: [2, 2, 3, 1]
21 | *
22 | * Output: 1
23 | *
24 | * Explanation: Note that the third maximum here means the third maximum distinct number.
25 | * Both numbers with value 2 are both considered as second maximum.
26 | */
27 | public class ThirdMaximumNumber {
28 | /**
29 | * Main method
30 | *
31 | * @param args
32 | * @throws Exception
33 | */
34 | public static void main(String[] args) throws Exception {
35 | int[] a = {1, 2};
36 | System.out.println(new ThirdMaximumNumber().thirdMax(a));
37 | }
38 |
39 | public int thirdMax(int[] nums) {
40 | long[] max = {Long.MIN_VALUE, Long.MIN_VALUE, Long.MIN_VALUE};
41 | int count = 0;
42 | for (int num : nums) {
43 | for (int j = 0; j < 3; j++) {
44 | if (max[j] > num) continue;
45 | else if (max[j] == num) break;
46 | int k = j;
47 | long temp1, temp2;
48 | temp1 = num;
49 | count++;
50 | while (k < 3) {
51 | temp2 = max[k];
52 | max[k] = temp1;
53 | temp1 = temp2;
54 | k++;
55 | }
56 | break;
57 | }
58 | }
59 | System.out.println(Integer.MIN_VALUE);
60 | return (count >= 3) ? (int) max[2] : (int) max[0];
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/problems/src/array/CanPlaceFlowers.java:
--------------------------------------------------------------------------------
1 | package array;
2 |
3 | /**
4 | * Created by gouthamvidyapradhan on 10/06/2017.
5 | * Accepted
6 | *
7 | * Suppose you have a long flowerbed in which some of the plots are planted and some are not. However, flowers cannot be planted in adjacent plots - they would compete for water and both would die.
8 | *
9 | * Given a flowerbed (represented as an array containing 0 and 1, where 0 means empty and 1 means not empty), and a number n, return if n new flowers can be planted in it without violating the no-adjacent-flowers rule.
10 | *
11 | * Example 1:
12 | * Input: flowerbed = [1,0,0,0,1], n = 1
13 | * Output: True
14 | * Example 2:
15 | * Input: flowerbed = [1,0,0,0,1], n = 2
16 | * Output: False
17 | * Note:
18 | * The input array won't violate no-adjacent-flowers rule.
19 | * The input array size is in the range of [1, 20000].
20 | * n is a non-negative integer which won't exceed the input array size.
21 | */
22 | public class CanPlaceFlowers {
23 | /**
24 | * Main method
25 | *
26 | * @param args
27 | * @throws Exception
28 | */
29 | public static void main(String[] args) throws Exception {
30 | int[] n = {1, 0, 0, 0, 1};
31 | System.out.println(new CanPlaceFlowers().canPlaceFlowers(n, 1));
32 | }
33 |
34 | public boolean canPlaceFlowers(int[] flowerbed, int n) {
35 |
36 | int[] T = new int[flowerbed.length + 4];
37 | for (int i = 0, j = 2; i < flowerbed.length; i++)
38 | T[j++] = flowerbed[i];
39 | T[0] = 1;
40 | T[T.length - 1] = 1;
41 | int total = 0, count = 0;
42 | for (int i = 1; i < T.length; i++) {
43 | if (T[i] == 0)
44 | count++;
45 | else {
46 | if ((count % 2) == 0)
47 | total += ((count / 2) - 1);
48 | else
49 | total += (count / 2);
50 | count = 0; //reset
51 | }
52 | }
53 | return (total >= n);
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/problems/src/greedy/BurstBalloons.java:
--------------------------------------------------------------------------------
1 | package greedy;
2 |
3 | import java.util.Arrays;
4 |
5 | /**
6 | * Created by gouthamvidyapradhan on 28/06/2017.
7 | *
8 | * There are a number of spherical balloons spread in two-dimensional space. For each balloon, provided input is the start and end coordinates of the horizontal diameter. Since it's horizontal, y-coordinates don't matter and hence the x-coordinates of start and end of the diameter suffice. Start is always smaller than end. There will be at most 104 balloons.
9 | *
10 | * An arrow can be shot up exactly vertically from different points along the x-axis. A balloon with xstart and xend bursts by an arrow shot at x if xstart ≤ x ≤ xend. There is no limit to the number of arrows that can be shot. An arrow once shot keeps travelling up infinitely. The problem is to find the minimum number of arrows that must be shot to burst all balloons.
11 | *
12 | * Example:
13 | *
14 | * Input:
15 | * [[10,16], [2,8], [1,6], [7,12]]
16 | *
17 | * Output:
18 | * 2
19 | *
20 | * Explanation:
21 | * One way is to shoot one arrow for example at x = 6 (bursting the balloons [2,8] and [1,6]) and another arrow at x
22 | */
23 | public class BurstBalloons {
24 | /**
25 | * Main method
26 | *
27 | * @param args
28 | * @throws Exception
29 | */
30 | public static void main(String[] args) throws Exception {
31 | int[][] baloons = {{10, 16}, {2, 8}, {1, 6}, {7, 12}};
32 | System.out.println(new BurstBalloons().findMinArrowShots(baloons));
33 | }
34 |
35 | public int findMinArrowShots(int[][] points) {
36 | if (points.length == 0) return 0;
37 | Arrays.sort(points, ((o1, o2) -> o1[1] - o2[1]));
38 | int count = 0;
39 | int leftMost = points[0][1];
40 | for (int i = 1; i < points.length; i++) {
41 | if (leftMost < points[i][0]) {
42 | count++;
43 | leftMost = points[i][1];
44 | }
45 | }
46 | return count + 1;
47 | }
48 |
49 | }
50 |
--------------------------------------------------------------------------------
/problems/src/hashing/MaximumSizeSubarraySumEqualsk.java:
--------------------------------------------------------------------------------
1 | package hashing;
2 |
3 | import java.util.HashMap;
4 | import java.util.Map;
5 |
6 | /**
7 | * Created by gouthamvidyapradhan on 18/10/2017.
8 | * Given an array nums and a target value k, find the maximum length of a subarray that sums to k. If there isn't
9 | * one, return 0 instead.
10 |
11 | Note:
12 | The sum of the entire nums array is guaranteed to fit within the 32-bit signed integer range.
13 |
14 | Example 1:
15 | Given nums = [1, -1, 5, -2, 3], k = 3,
16 | return 4. (because the subarray [1, -1, 5, -2] sums to 3 and is the longest)
17 |
18 | Example 2:
19 | Given nums = [-2, -1, 2, 1], k = 1,
20 | return 2. (because the subarray [-1, 2] sums to 1 and is the longest)
21 |
22 | Follow Up:
23 | Can you do it in O(n) time?
24 | */
25 | public class MaximumSizeSubarraySumEqualsk {
26 |
27 | /**
28 | * Main method
29 | * @param args
30 | * @throws Exception
31 | */
32 | public static void main(String[] args) throws Exception{
33 | int[] A = {1,-1,5,-2,3};
34 | System.out.println(new MaximumSizeSubarraySumEqualsk().maxSubArrayLen(A, 10));
35 | }
36 |
37 | public int maxSubArrayLen(int[] nums, int k) {
38 | Map
9 | * Note: You can assume that
10 | *
11 | * 0 <= amount <= 5000
12 | * 1 <= coin <= 5000
13 | * the number of coins is less than 500
14 | * the answer is guaranteed to fit into signed 32-bit integer
15 | * Example 1:
16 | *
17 | * Input: amount = 5, coins = [1, 2, 5]
18 | * Output: 4
19 | * Explanation: there are four ways to make up the amount:
20 | * 5=5
21 | * 5=2+2+1
22 | * 5=2+1+1+1
23 | * 5=1+1+1+1+1
24 | * Example 2:
25 | *
26 | * Input: amount = 3, coins = [2]
27 | * Output: 0
28 | * Explanation: the amount of 3 cannot be made up just with coins of 2.
29 | * Example 3:
30 | *
31 | * Input: amount = 10, coins = [10]
32 | * Output: 1
33 | */
34 | public class CoinChange2 {
35 | /**
36 | * Main method
37 | *
38 | * @param args
39 | * @throws Exception
40 | */
41 | public static void main(String[] args) throws Exception {
42 | int[] coins = {1, 2, 5};
43 | System.out.println(new CoinChange2().change(5, coins));
44 | }
45 |
46 | public int change(int amount, int[] coins) {
47 | int[][] dp = new int[coins.length][amount + 1];
48 | for (int i = 0, l = coins.length; i < l; i++)
49 | Arrays.fill(dp[i], -1);
50 | return dp(dp, 0, coins, coins.length, amount);
51 | }
52 |
53 | private int dp(int[][] dp, int i, int[] coins, int l, int n) {
54 | if (n == 0) return 1;
55 | else if (i >= l) return 0;
56 | if (n < 0) return 0;
57 | if (dp[i][n] != -1) return dp[i][n];
58 | dp[i][n] = dp(dp, i + 1, coins, l, n) + dp(dp, i, coins, l, n - coins[i]);
59 | return dp[i][n];
60 | }
61 |
62 | }
63 |
--------------------------------------------------------------------------------
/problems/src/backtracking/CombinationSumII.java:
--------------------------------------------------------------------------------
1 | package backtracking;
2 |
3 | import java.util.ArrayList;
4 | import java.util.Arrays;
5 | import java.util.List;
6 |
7 | /**
8 | * Created by gouthamvidyapradhan on 14/03/2017.
9 | * Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
10 | *
11 | * Each number in C may only be used once in the combination.
12 | *
13 | * Note:
14 | * All numbers (including target) will be positive integers.
15 | * The solution set must not contain duplicate combinations.
16 | * For example, given candidate set [10, 1, 2, 7, 6, 1, 5] and target 8,
17 | * A solution set is:
18 | * [
19 | * [1, 7],
20 | * [1, 2, 5],
21 | * [2, 6],
22 | * [1, 1, 6]
23 | * ]
24 | */
25 |
26 | public class CombinationSumII {
27 | /**
28 | * Main method
29 | *
30 | * @param args
31 | * @throws Exception
32 | */
33 | public static void main(String[] args) throws Exception {
34 | int[] candidates = {1, 1, 2, 2};
35 | List
11 | * Note: The solution set must not contain duplicate triplets.
12 | *
13 | * For example, given array S = [-1, 0, 1, 2, -1, -4],
14 | *
15 | * A solution set is:
16 | * [
17 | * [-1, 0, 1],
18 | * [-1, -1, 2]
19 | * ]
20 | */
21 | public class ThreeSum {
22 | /**
23 | * Main method
24 | *
25 | * @param args
26 | * @throws Exception
27 | */
28 | public static void main(String[] args) throws Exception {
29 | int[] nums = {-1, 0, 1, 2, -1, -4, -1, 0, 1, 2, -1, -4, -1, 0, 1, 2, -1, -4, -1, 0, 1, 2, -1, -4, -1, 0, 1, 2, -1, -4, -1, 0, 1, 2, -1, -4, -1, 0, 1, 2, -1, -4, -1, 0, 1, 2, -1, -4};
30 | System.out.println(new ThreeSum().threeSum(nums));
31 | }
32 |
33 | public List
10 | * The same repeated number may be chosen from C unlimited number of times.
11 | *
12 | * Note:
13 | * All numbers (including target) will be positive integers.
14 | * The solution set must not contain duplicate combinations.
15 | * For example, given candidate set [2, 3, 6, 7] and target 7,
16 | * A solution set is:
17 | * [
18 | * [7],
19 | * [2, 2, 3]
20 | * ]
21 | */
22 | public class CombinationSum {
23 | /**
24 | * Main method
25 | *
26 | * @param args
27 | * @throws Exception
28 | */
29 | public static void main(String[] args) throws Exception {
30 | int[] candidates = {2, 3, 6, 7};
31 |
32 | List
10 | * For example, given array S = {-1 2 1 -4}, and target = 1.
11 | *
12 | * The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
13 | */
14 | public class ThreeSumClosest {
15 |
16 | public static void main(String[] args) {
17 | int[] a = {-1, 2, 1, -4};
18 | System.out.println(new ThreeSumClosest().threeSumClosest(a, 1));
19 | }
20 |
21 | public int threeSumClosest(int[] a, int target) {
22 | Arrays.sort(a);
23 | int min = Integer.MAX_VALUE, ans = -1;
24 | for (int i = 0, l = a.length; i < l - 2; i++) {
25 | if (i == 0 || !(a[i] == a[i - 1])) {
26 | int j = i + 1, k = l - 1;
27 | while (k > j) {
28 | if (j != i + 1 && (a[j] == a[j - 1])) {
29 | j++;
30 | continue;
31 | }
32 | int sum = a[i] + a[j] + a[k];
33 | if (sum < target) {
34 | int diff = Math.abs(sum - target);
35 | if (diff < min) {
36 | min = diff;
37 | ans = sum;
38 | }
39 | j++;
40 | } else if (sum > target) {
41 | int diff = Math.abs(sum - target);
42 | if (diff < min) {
43 | min = diff;
44 | ans = sum;
45 | }
46 | k--;
47 | } else {
48 | return sum;
49 | }
50 | }
51 | }
52 | }
53 | return ans;
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/problems/src/stack/MinStack.java:
--------------------------------------------------------------------------------
1 | package stack;
2 |
3 | import java.util.Stack;
4 |
5 | /**
6 | * Created by gouthamvidyapradhan on 08/03/2017.
7 | * Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
8 | *
9 | * push(x) -- Push element x onto stack.
10 | * pop() -- Removes the element on top of the stack.
11 | * top() -- Get the top element.
12 | * getMin() -- Retrieve the minimum element in the stack.
13 | * Example:
14 | * MinStack minStack = new MinStack();
15 | * minStack.push(-2);
16 | * minStack.push(0);
17 | * minStack.push(-3);
18 | * minStack.getMin(); --> Returns -3.
19 | * minStack.pop();
20 | * minStack.top(); --> Returns 0.
21 | * minStack.getMin(); --> Returns -2.
22 | */
23 | public class MinStack {
24 | class Node {
25 | int value, min;
26 |
27 | Node(int value, int min) {
28 | this.value = value;
29 | this.min = min;
30 | }
31 | }
32 |
33 | private Stack
7 | * Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.
8 | *
9 | * Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.
10 | */
11 | public class StringToInteger {
12 | /**
13 | * Main method
14 | *
15 | * @param args
16 | * @throws Exception
17 | */
18 | public static void main(String[] args) throws Exception {
19 | System.out.println(new StringToInteger().myAtoi(" 2147483649a sdfasdf"));
20 | }
21 |
22 | public int myAtoi(String str) {
23 | boolean isPositive = true;
24 | if (str == null || str.trim().isEmpty()) return 0;
25 | str = str.trim();
26 | if (str.charAt(0) == '+') {
27 | isPositive = true;
28 | str = str.substring(1, str.length());
29 | } else if (str.charAt(0) == '-') {
30 | isPositive = false;
31 | str = str.substring(1, str.length());
32 | } else if (str.charAt(0) > '9' || str.charAt(0) < '0')
33 | return 0;
34 | int i = 0;
35 | for (int l = str.length(); i < l; i++) {
36 | if (str.charAt(i) > '9' || str.charAt(i) < '0')
37 | break;
38 | }
39 | str = str.substring(0, i);
40 | long num = 0;
41 | for (int j = 0, l = str.length(); j < l; j++) {
42 | int n = (str.charAt(j) - '0');
43 | num *= 10;
44 | num += n;
45 | if (isPositive) {
46 | if (num > Integer.MAX_VALUE) return Integer.MAX_VALUE;
47 | } else {
48 | if ((num * -1) < Integer.MIN_VALUE) return Integer.MIN_VALUE;
49 | }
50 | }
51 | if (isPositive)
52 | return (int) num;
53 | else return (int) (num * -1);
54 | }
55 |
56 |
57 | }
58 |
--------------------------------------------------------------------------------
/problems/src/tree/BinarayTreeRightSideView.java:
--------------------------------------------------------------------------------
1 | package tree;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | /**
7 | * Created by gouthamvidyapradhan on 12/03/2017.
8 | * Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.
9 | *
10 | * For example:
11 | * Given the following binary tree,
12 | * 1 <---
13 | * / \
14 | * 2 3 <---
15 | * \ \
16 | * 5 4 <---
17 | * You should return [1, 3, 4].
18 | */
19 |
20 | public class BinarayTreeRightSideView {
21 | public static class TreeNode {
22 | int val;
23 | TreeNode left;
24 | TreeNode right;
25 |
26 | TreeNode(int x) {
27 | val = x;
28 | }
29 | }
30 |
31 | private int maxHeigh = Integer.MIN_VALUE;
32 | List
7 | * For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root.
8 | *
9 | * For example:
10 | * Given the below binary tree,
11 | *
12 | * 1
13 | * / \
14 | * 2 3
15 | * Return 6.
16 | */
17 | public class BinaryTreeMaximumPathSum {
18 | public static class TreeNode {
19 | int val;
20 | TreeNode left;
21 | TreeNode right;
22 |
23 | TreeNode(int x) {
24 | val = x;
25 | }
26 | }
27 |
28 | private int max = Integer.MIN_VALUE;
29 |
30 | /**
31 | * Main method
32 | *
33 | * @param args
34 | * @throws Exception
35 | */
36 | public static void main(String[] args) throws Exception {
37 | TreeNode root = new TreeNode(5);
38 | root.left = new TreeNode(4);
39 | root.left.left = new TreeNode(3);
40 | root.left.left.left = new TreeNode(-1);
41 | root.right = new TreeNode(7);
42 | root.right.left = new TreeNode(2);
43 | root.right.left.left = new TreeNode(9);
44 | System.out.println(new BinaryTreeMaximumPathSum().maxPathSum(root));
45 | }
46 |
47 | public int maxPathSum(TreeNode root) {
48 | if (root == null) return 0;
49 | dfs(root);
50 | return max;
51 | }
52 |
53 | private int dfs(TreeNode root) {
54 | if (root == null) return 0;
55 | int left = dfs(root.left);
56 | int right = dfs(root.right);
57 | max = Math.max(max, root.val);
58 | max = Math.max(max, root.val + left);
59 | max = Math.max(max, root.val + right);
60 | max = Math.max(max, root.val + left + right);
61 | int leftVal = Math.max(root.val, root.val + left);
62 | int rightVal = Math.max(root.val, root.val + right);
63 | return Math.max(leftVal, rightVal);
64 | }
65 | }
66 |
--------------------------------------------------------------------------------
> result = new Subsets().subsets(n);
36 | }
37 |
38 | public List
> subsets(int[] nums) {
39 | List
> result = new ArrayList<>();
40 | result.add(new ArrayList<>()); //empty subset
41 | for (int i = 0, l = nums.length; i < l; i++) {
42 | for (int j = 0, resLen = result.size(); j < resLen; j++) {
43 | List
> result = new Combinations().combine(3, 3);
26 | }
27 |
28 | public List
> combine(int n, int k) {
29 | int[] subArr = new int[k];
30 | List
> result = new ArrayList<>();
31 | getNext(0, 0, n, k, subArr, result);
32 | return result;
33 | }
34 |
35 | private void getNext(int i, int count,
36 | int n, int k, int[] subArr, List
> result) {
37 | if (k == 0) {
38 | List
> permuteUnique(int[] nums) {
26 | List
> result = new ArrayList<>();
27 | Arrays.sort(nums);
28 | nextPermutation(0, nums, result);
29 | return result;
30 | }
31 |
32 | private void nextPermutation(int i, int[] nums, List
> result) {
33 | if (i == nums.length - 1) {
34 | List
> result = new Permutations().permute(nums);
31 | }
32 |
33 | public List
> permute(int[] nums) {
34 | List
> result = new ArrayList<>();
35 | nextPermutation(0, nums, result);
36 | return result;
37 | }
38 |
39 | private void nextPermutation(int i, int[] nums, List
> result) {
40 | if (i == nums.length - 1) {
41 | List
> result = new SubsetsII().subsetsWithDup(n);
35 | }
36 |
37 | public List
> subsetsWithDup(int[] nums) {
38 | List
> result = new ArrayList<>();
39 | result.add(new ArrayList<>()); //empty subset
40 | int start = 0, newStart = 0;
41 | Arrays.sort(nums);
42 | for (int i = 0, l = nums.length; i < l; i++) {
43 | newStart = result.size();
44 | if (i == 0 || nums[i] != nums[i - 1]) {
45 | start = 0;
46 | }
47 | for (int j = start, resLen = result.size(); j < resLen; j++) {
48 | List
> zigzagLevelOrder(TreeNode root) {
42 | List
> result = new ArrayList<>();
43 | if (root == null) return result;
44 | dfs(root, 0, result);
45 | return result;
46 | }
47 |
48 | @SuppressWarnings("unchecked")
49 | private void dfs(TreeNode root, int level, List
> result) {
50 | if (root != null) {
51 | LinkedList
> result = new PalindromePartitioning().partition("aaaaaaaaaaaaaaaaaa");
29 | }
30 |
31 | public List
> partition(String s) {
32 | List
> result = new ArrayList<>();
33 | doNext(0, new ArrayList<>(), s, result);
34 | return result;
35 | }
36 |
37 | private void doNext(int i, List
> result) {
38 | if (i == s.length()) {
39 | List
> result = new CombinationSumII().combinationSum2(candidates, 4);
36 | }
37 |
38 | public List
> combinationSum2(int[] candidates, int target) {
39 | Arrays.sort(candidates);
40 | List
> result = new ArrayList<>();
41 | combination(0, target, candidates, new ArrayList<>(), result);
42 | return result;
43 | }
44 |
45 | private void combination(int i, int target, int[] candidates, List
> result) {
46 | if (target == 0) {
47 | result.add(new ArrayList<>(row));
48 | } else if (target > 0) {
49 | for (int j = i, l = candidates.length; j < l; j++) {
50 | if (j > i && candidates[j] == candidates[j - 1]) continue;
51 | row.add(candidates[j]);
52 | combination(j + 1, target - candidates[j], candidates, row, result);
53 | row.remove(row.size() - 1);
54 | }
55 | }
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/problems/src/dynamic_programming/PalindromicSubstrings.java:
--------------------------------------------------------------------------------
1 | package dynamic_programming;
2 |
3 | /**
4 | * Created by gouthamvidyapradhan on 13/12/2017.
5 | *
6 | * Given a string, your task is to count how many palindromic substrings in this string.
7 |
8 | The substrings with different start indexes or end indexes are counted as different substrings even they consist of
9 | same characters.
10 |
11 | Example 1:
12 | Input: "abc"
13 | Output: 3
14 | Explanation: Three palindromic strings: "a", "b", "c".
15 | Example 2:
16 | Input: "aaa"
17 | Output: 6
18 | Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".
19 | Note:
20 | The input string length won't exceed 1000.
21 |
22 | Solution O(n ^ 2): Example abcba: Compare char at two indices each time for example if char at
23 | index 0 and index 4 are equal and if substring 1 and 3 is a palindrome then, sub-string 0 and 4 is also a palindrome
24 |
25 | */
26 | public class PalindromicSubstrings {
27 |
28 | /**
29 | * Main method
30 | * @param args
31 | */
32 | public static void main(String[] args) {
33 | System.out.println(new PalindromicSubstrings().countSubstrings("aaa"));
34 | }
35 |
36 | public int countSubstrings(String s) {
37 | boolean[][] T = new boolean[s.length()][s.length()];
38 | int count = s.length();
39 | for(int i = 0, j = 0; i < T.length; i ++, j ++){
40 | T[i][j] = true;
41 | }
42 |
43 | for(int k = 1, col = s.length(); k < col; k++){
44 | for(int i = 0, j = k; i < col && j < col; i++, j++){
45 | if(k == 1){
46 | if(s.charAt(i) == s.charAt(j)){
47 | T[i][j] = true;
48 | count++;
49 | }
50 | } else{
51 | if(s.charAt(i) == s.charAt(j) && T[i + 1][j - 1]){
52 | T[i][j] = true;
53 | count++;
54 | }
55 | }
56 | }
57 | }
58 | return count;
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/problems/src/two_pointers/ThreeSum.java:
--------------------------------------------------------------------------------
1 | package two_pointers;
2 |
3 | import java.util.ArrayList;
4 | import java.util.Arrays;
5 | import java.util.List;
6 |
7 | /**
8 | * Created by gouthamvidyapradhan on 29/03/2017.
9 | * Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
10 | *
> threeSum(int[] nums) {
34 | List
> result = new ArrayList<>();
35 | if (nums.length < 3) return result;
36 | Arrays.sort(nums);
37 | for (int i = 0, l = nums.length; i < l - 2; i++) {
38 | if (i == 0 || nums[i] != nums[i - 1]) {
39 | int j = i + 1, k = l - 1;
40 | while (k > j) {
41 | if (j != i + 1 && nums[j] == nums[j - 1]) {
42 | j++;
43 | continue;
44 | }
45 | int sum = nums[i] + nums[j] + nums[k];
46 | if (sum == 0) {
47 | result.add(Arrays.asList(nums[i], nums[j], nums[k]));
48 | k--;
49 | j++;
50 | } else if (sum > 0) k--;
51 | else j++;
52 | }
53 | }
54 | }
55 | return result;
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/problems/src/backtracking/CombinationSum.java:
--------------------------------------------------------------------------------
1 | package backtracking;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | /**
7 | * Created by pradhang on 3/14/2017.
8 | * Given a set of candidate numbers (C) (without duplicates) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
9 | *
> result = new CombinationSum().combinationSum(candidates, 7);
33 | }
34 |
35 | public List
> combinationSum(int[] candidates, int target) {
36 | List
> result = new ArrayList<>();
37 | List
> result, int count, int[] candidates, int target, List