└── 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 binaryTreePaths(TreeNode root) { 31 | List result = new ArrayList<>(); 32 | new BinaryTreePaths().inorder(root, result, ""); 33 | return result; 34 | } 35 | 36 | private void inorder(TreeNode node, List list, String path){ 37 | if(node != null){ 38 | if(node.left == null && node.right == null){ 39 | list.add(path + node.val); 40 | } else { 41 | inorder(node.left, list, path + node.val + "->"); 42 | inorder(node.right, list, path + node.val + "->"); 43 | } 44 | } 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /problems/src/binary_search/HIndexII.java: -------------------------------------------------------------------------------- 1 | package binary_search; 2 | 3 | /** 4 | * Created by gouthamvidyapradhan on 11/12/2017. 5 | * 6 | * Follow up for H-Index: What if the citations array is sorted in ascending order? Could you optimize your algorithm? 7 | * @see array.HIndex 8 | */ 9 | public class HIndexII { 10 | /** 11 | * Main method 12 | * @param args 13 | * @throws Exception 14 | */ 15 | public static void main(String[] args) throws Exception{ 16 | int[] A = {1, 1, 1, 1, 1, 15, 20}; 17 | System.out.println(new HIndexII().hIndex(A)); 18 | } 19 | 20 | public int hIndex(int[] citations) { 21 | if(citations.length == 0) return 0; 22 | int s = 0, e = citations.length; 23 | int ans = -1; 24 | while(s < e){ 25 | int m = (s + e) >>> 1; 26 | int cit = citations.length - m; 27 | if(citations[m] > cit){ 28 | if(ans < cit){ 29 | ans = cit; 30 | } 31 | e = m; 32 | } else{ 33 | if(ans < citations[m]){ 34 | ans = citations[m]; 35 | } 36 | s = m + 1; 37 | } 38 | } 39 | return ans; 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /problems/src/greedy/JumpGameII.java: -------------------------------------------------------------------------------- 1 | package greedy; 2 | 3 | /** 4 | * Created by gouthamvidyapradhan on 02/04/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 | * 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 generateParenthesis(int n) { 26 | List list = new ArrayList<>(); 27 | backTrack(list, "", 0, 0, n); 28 | return list; 29 | } 30 | 31 | private void backTrack(List list, String str, int open, int close, int n) { 32 | if (str.length() == n * 2) { 33 | list.add(str); 34 | } else { 35 | if (open < n) 36 | backTrack(list, str.concat("("), open + 1, close, n); 37 | if (close < open) //number of close should be less than open or else it can result in unbalanced parentheses 38 | backTrack(list, str.concat(")"), open, close + 1, n); 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /problems/src/math/RomanToInteger.java: -------------------------------------------------------------------------------- 1 | package math; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | /** 7 | * Created by gouthamvidyapradhan on 12/08/2017. 8 | *

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 map = new HashMap<>(); 26 | map.put('I', 1); 27 | map.put('V', 5); 28 | map.put('X', 10); 29 | map.put('L', 50); 30 | map.put('C', 100); 31 | map.put('D', 500); 32 | map.put('M', 1000); 33 | 34 | String str = new StringBuilder(s).reverse().toString(); 35 | int sum = 0, prev = -1; 36 | for (int i = 0, l = str.length(); i < l; i++) { 37 | int curr = map.get(str.charAt(i)); 38 | if (curr < prev) { 39 | sum -= curr; 40 | } else { 41 | sum += curr; 42 | } 43 | prev = curr; 44 | } 45 | 46 | return sum; 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /problems/src/array/RotateArray.java: -------------------------------------------------------------------------------- 1 | package array; 2 | 3 | /** 4 | * Created by gouthamvidyapradhan on 01/08/2017. 5 | * Rotate an array of n elements to the right by k steps. 6 | *

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> 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 newList = new ArrayList<>(result.get(j)); 44 | newList.add(nums[i]); 45 | result.add(newList); 46 | } 47 | } 48 | return result; 49 | } 50 | 51 | } 52 | -------------------------------------------------------------------------------- /problems/src/dynamic_programming/HouseRobber.java: -------------------------------------------------------------------------------- 1 | package dynamic_programming; 2 | 3 | /** 4 | * Created by pradhang on 4/3/2017. 5 | * You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night. 6 | *

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 result = new GrayCode().grayCode(3); 35 | } 36 | 37 | public List grayCode(int n) { 38 | List result = new ArrayList<>(); 39 | for (int i = 0; i <= ((1 << n) - 1); i++) 40 | result.add(i ^ (i >> 1)); 41 | return result; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /problems/src/backtracking/Combinations.java: -------------------------------------------------------------------------------- 1 | package backtracking; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | /** 7 | * Created by pradhang on 3/8/2017. 8 | * Given two integers n and k, return all possible combinations of k numbers out of 1 ... n. 9 | *

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> 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 subList = new ArrayList<>(); 39 | for (int a : subArr) 40 | subList.add(a); 41 | result.add(subList); 42 | } else { 43 | for (int j = i + 1; j <= n; j++) { 44 | subArr[count] = j; 45 | getNext(j, count + 1, n, k - 1, subArr, result); 46 | } 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /problems/src/array/PascalsTriangle.java: -------------------------------------------------------------------------------- 1 | package array; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Arrays; 5 | import java.util.List; 6 | 7 | /** 8 | * Created by gouthamvidyapradhan on 25/03/2017. 9 | *

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 getRow(int rowIndex) { 24 | int k = rowIndex; 25 | if (k == 0) 26 | return Arrays.asList(1); 27 | else if (k == 1) 28 | return Arrays.asList(1, 1); 29 | else if (k == 2) 30 | return Arrays.asList(1, 2, 1); 31 | List result = new ArrayList<>(); 32 | result.add(2); 33 | k = k - 2; 34 | int p, c; 35 | while (k-- > 0) { 36 | p = 1; 37 | int i = 0; 38 | for (int l = result.size(); i < l; i++) { 39 | c = result.get(i); 40 | result.set(i, p + c); 41 | p = c; 42 | } 43 | result.add(p + 1); 44 | } 45 | result.add(0, 1); 46 | result.add(1); 47 | return result; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /problems/src/string/ValidPalindromeII.java: -------------------------------------------------------------------------------- 1 | package string; 2 | 3 | /** 4 | * Created by gouthamvidyapradhan on 09/12/2017. 5 | * Given a non-empty string s, you may delete at most one character. Judge whether you can make it a palindrome. 6 | 7 | Example 1: 8 | Input: "aba" 9 | Output: True 10 | Example 2: 11 | Input: "abca" 12 | Output: True 13 | Explanation: You could delete the character 'c'. 14 | Note: 15 | The string will only contain lowercase characters a-z. The maximum length of the string is 50000. 16 | */ 17 | public class ValidPalindromeII { 18 | 19 | /** 20 | * Main method 21 | * @param args 22 | * @throws Exception 23 | */ 24 | public static void main(String[] args) throws Exception{ 25 | System.out.println(new ValidPalindromeII().validPalindrome("aaaaaab")); 26 | } 27 | 28 | public boolean validPalindrome(String s) { 29 | for(int i = 0, j = s.length() - 1; i < j;){ 30 | if(s.charAt(i) == s.charAt(j)){ 31 | i++; j--; 32 | } else { 33 | return isPaliandrome(s.substring(i, j)) || isPaliandrome(s.substring(i + 1, j + 1)); 34 | } 35 | } 36 | return true; 37 | } 38 | 39 | private boolean isPaliandrome(String s){ 40 | for(int i = 0, j = s.length() - 1; i < j;){ 41 | if(s.charAt(i) == s.charAt(j)){ 42 | i++; j--; 43 | } else return false; 44 | } 45 | return true; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /problems/src/array/IncreasingTripletSubsequence.java: -------------------------------------------------------------------------------- 1 | package array; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | * Created by gouthamvidyapradhan on 17/12/2017. 7 | * Given an unsorted array return whether an increasing subsequence of length 3 exists or not in the array. 8 | 9 | Formally the function should: 10 | Return true if there exists i, j, k 11 | such that arr[i] < arr[j] < arr[k] given 0 ≤ i < j < k ≤ n-1 else return false. 12 | Your algorithm should run in O(n) time complexity and O(1) space complexity. 13 | 14 | Examples: 15 | Given [1, 2, 3, 4, 5], 16 | return true. 17 | 18 | Given [5, 4, 3, 2, 1], 19 | return false. 20 | */ 21 | public class IncreasingTripletSubsequence { 22 | 23 | /** 24 | * Main method 25 | * @param args 26 | * @throws Exception 27 | */ 28 | public static void main(String[] args) throws Exception{ 29 | int[] A = {1, 2, 3, 4, 5}; 30 | System.out.println(new IncreasingTripletSubsequence().increasingTriplet(A)); 31 | } 32 | 33 | public boolean increasingTriplet(int[] nums) { 34 | int[] A = new int[3]; 35 | Arrays.fill(A, Integer.MAX_VALUE); 36 | for (int num : nums) { 37 | if (num < A[0]) { 38 | A[0] = num; 39 | } else if (num < A[1] && num > A[0]) { 40 | A[1] = num; 41 | } else if (num < A[2] && num > A[1]) { 42 | return true; 43 | } 44 | } 45 | return false; 46 | } 47 | } 48 | 49 | -------------------------------------------------------------------------------- /problems/src/string/ValidPalindrome.java: -------------------------------------------------------------------------------- 1 | package string; 2 | 3 | /** 4 | * Created by gouthamvidyapradhan on 13/07/2017. 5 | * Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. 6 | *

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 list = new LinkedList<>(); 33 | for (int[] p : people) 34 | list.add(p[1], p); 35 | int[][] result = new int[people.length][2]; 36 | for (int i = 0, l = list.size(); i < l; i++) 37 | result[i] = list.get(i); 38 | return result; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /problems/src/linked_list/LinkedListCycle.java: -------------------------------------------------------------------------------- 1 | package linked_list; 2 | 3 | import java.util.HashSet; 4 | import java.util.Set; 5 | 6 | /** 7 | * Created by gouthamvidyapradhan on 23/02/2017. 8 | * Given a linked list, determine if it has a cycle in it. 9 | *

10 | * Follow up: 11 | * Can you solve it without using extra space? 12 | */ 13 | public class LinkedListCycle { 14 | private static Set hashCode = new HashSet<>(); 15 | 16 | static class ListNode { 17 | int val; 18 | ListNode next; 19 | 20 | ListNode(int x) { 21 | val = x; 22 | next = null; 23 | } 24 | } 25 | 26 | /** 27 | * Main method 28 | * 29 | * @param args 30 | */ 31 | public static void main(String[] args) throws Exception { 32 | ListNode node1 = new ListNode(1); 33 | ListNode node2 = new ListNode(2); 34 | ListNode node3 = new ListNode(3); 35 | node1.next = node2; 36 | node2.next = node3; 37 | node3.next = node1; 38 | System.out.println(new LinkedListCycle().hasCycle(node1)); 39 | } 40 | 41 | public boolean hasCycle(ListNode head) { 42 | ListNode slow = head; 43 | ListNode fast = head; 44 | while (slow != null && fast != null) { 45 | slow = slow.next; 46 | fast = fast.next; 47 | if (fast != null) 48 | fast = fast.next; 49 | else break; 50 | if (fast != null && slow != null) 51 | if (fast.equals(slow)) return true; 52 | } 53 | return false; 54 | } 55 | 56 | } 57 | -------------------------------------------------------------------------------- /problems/src/array/TwoSumII.java: -------------------------------------------------------------------------------- 1 | package array; 2 | 3 | /** 4 | * Created by gouthamvidyapradhan on 18/03/2017. 5 | * Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number. 6 | *

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 set, int k){ 55 | if(node != null){ 56 | int req = k - (node.val); 57 | if(set.contains(req)){ 58 | return true; 59 | } 60 | set.add(node.val); 61 | if(inorder(node.left, set, k)){ 62 | return true; 63 | } else{ 64 | if(inorder(node.right, set, k)){ 65 | return true; 66 | } 67 | } 68 | } return false; 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /problems/src/array/LongestIncreasingSubsequence.java: -------------------------------------------------------------------------------- 1 | package array; 2 | 3 | /** 4 | * Created by gouthamvidyapradhan on 03/12/2017. 5 | * 6 | * Given an unsorted array of integers, find the length of longest continuous increasing subsequence (subarray). 7 | 8 | Example 1: 9 | Input: [1,3,5,4,7] 10 | Output: 3 11 | Explanation: The longest continuous increasing subsequence is [1,3,5], its length is 3. 12 | Even though [1,3,5,7] is also an increasing subsequence, it's not a continuous one where 5 and 7 are separated by 4. 13 | Example 2: 14 | Input: [2,2,2,2,2] 15 | Output: 1 16 | Explanation: The longest continuous increasing subsequence is [2], its length is 1. 17 | Note: Length of the array will not exceed 10,000. 18 | */ 19 | public class LongestIncreasingSubsequence { 20 | 21 | /** 22 | * Main method 23 | * @param args 24 | * @throws Exception 25 | */ 26 | public static void main(String[] args) throws Exception{ 27 | int[] A = {1,3,5,4,7}; 28 | System.out.println(new LongestIncreasingSubsequence().findLengthOfLCIS(A)); 29 | } 30 | 31 | public int findLengthOfLCIS(int[] nums) { 32 | int max = 1, count = 1; 33 | if(nums.length == 1) return max; 34 | if(nums.length == 0) return 0; 35 | for(int i = 0, j = i + 1; j < nums.length;){ 36 | if(nums[j] > nums[i]){ 37 | count++; 38 | i++; j++; 39 | } else { 40 | max = Math.max(max, count); 41 | count = 0; 42 | i = j; 43 | j = i + 1; 44 | } 45 | } 46 | return max; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /problems/src/math/WaterAndJugProblem.java: -------------------------------------------------------------------------------- 1 | package math; 2 | 3 | import java.math.BigInteger; 4 | 5 | /** 6 | * Created by gouthamvidyapradhan on 29/07/2017. 7 | * You are given two jugs with capacities x and y litres. There is an infinite amount of water supply available. You need to determine whether it is possible to measure exactly z litres using these two jugs. 8 | *

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> 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 list = new ArrayList<>(); 35 | for (int n : nums) 36 | list.add(n); 37 | result.add(list); 38 | } else { 39 | for (int j = i, l = nums.length; j < l; j++) { 40 | if (j > i && nums[j] == nums[i]) continue; 41 | swap(nums, i, j); 42 | nextPermutation(i + 1, Arrays.copyOf(nums, nums.length), result); 43 | } 44 | } 45 | } 46 | 47 | private void swap(int[] a, int i, int j) { 48 | int tmp = a[i]; 49 | a[i] = a[j]; 50 | a[j] = tmp; 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /problems/src/dynamic_programming/BestTimeToBuyAndSellStocks.java: -------------------------------------------------------------------------------- 1 | package dynamic_programming; 2 | 3 | /** 4 | * Created by gouthamvidyapradhan on 17/03/2017. 5 | * Say you have an array for which the ith element is the price of a given stock on day i. 6 | *

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 set = new HashSet<>(); 22 | 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 LongestSubstringWitoutRepeats().lengthOfLongestSubstring("asdfsdfsdfsdfasdfdjdjjdjjdjjjjjajsdjjdjdjjd")); 31 | } 32 | 33 | private int lengthOfLongestSubstring(String s) { 34 | if (s == null || s.isEmpty()) return 0; 35 | Map map = new HashMap<>(); 36 | int i = 0, max = Integer.MIN_VALUE; 37 | for (int j = 0, l = s.length(); j < l; j++) { 38 | if (map.keySet().contains(s.charAt(j))) { 39 | i = Math.max(map.get(s.charAt(j)) + 1, i); 40 | } 41 | map.put(s.charAt(j), j); 42 | max = Math.max(max, (j - i) + 1); 43 | } 44 | return max; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /problems/src/design/EncodeAndDecodeTinyURL.java: -------------------------------------------------------------------------------- 1 | package design; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | /** 7 | * Created by gouthamvidyapradhan on 11/04/2017. 8 | * TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl and it returns a short URL such as http://tinyurl.com/4e9iAk. 9 | *

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 list = new ArrayList<>(); 14 | private static final String URL = "http://tinyurl.com/"; 15 | 16 | /** 17 | * Main method 18 | * 19 | * @param args 20 | * @throws Exception 21 | */ 22 | public static void main(String[] args) throws Exception { 23 | EncodeAndDecodeTinyURL encoder = new EncodeAndDecodeTinyURL(); 24 | String shorterUrl = encoder.encode("https://leetcode.com/problems/design-tinyurl"); 25 | System.out.println(encoder.decode(shorterUrl)); 26 | } 27 | 28 | // Encodes a URL to a shortened URL. 29 | public String encode(String longUrl) { 30 | list.add(longUrl); 31 | return URL.concat(String.valueOf(list.size())); 32 | } 33 | 34 | // Decodes a shortened URL to its original URL. 35 | public String decode(String shortUrl) { 36 | String[] parts = shortUrl.split("http://tinyurl.com/"); 37 | String code = parts[1]; 38 | return list.get(Integer.parseInt(code) - 1); 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /problems/src/tree/SameTree.java: -------------------------------------------------------------------------------- 1 | package tree; 2 | 3 | /** 4 | * Created by gouthamvidyapradhan on 23/01/2018. 5 | * Given two binary trees, write a function to check if they are the same or not. 6 | 7 | Two binary trees are considered the same if they are structurally identical and the nodes have the same value. 8 | 9 | 10 | Example 1: 11 | 12 | Input: 1 1 13 | / \ / \ 14 | 2 3 2 3 15 | 16 | [1,2,3], [1,2,3] 17 | 18 | Output: true 19 | Example 2: 20 | 21 | Input: 1 1 22 | / \ 23 | 2 2 24 | 25 | [1,2], [1,null,2] 26 | 27 | Output: false 28 | Example 3: 29 | 30 | Input: 1 1 31 | / \ / \ 32 | 2 1 1 2 33 | 34 | [1,2,1], [1,1,2] 35 | 36 | Output: false 37 | 38 | Solution: Do a pre-order traversal of both the trees in parallel and compare each node 39 | */ 40 | public class SameTree { 41 | 42 | public class TreeNode { 43 | int val; 44 | TreeNode left; 45 | TreeNode right; 46 | TreeNode(int x) { val = x; } 47 | } 48 | 49 | /** 50 | * Main method 51 | * @param args 52 | * @throws Exception 53 | */ 54 | public static void main(String[] args) throws Exception{ 55 | 56 | } 57 | 58 | public boolean isSameTree(TreeNode p, TreeNode q) { 59 | if((p == null && q != null) || (p != null && q == null)) return false; 60 | if(p == null && q == null) return true; 61 | else{ 62 | boolean status = isSameTree(p.left, q.left); 63 | if(!status || p.val != q.val){ 64 | return false; 65 | } 66 | return isSameTree(p.right, q.right); 67 | } 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /problems/src/backtracking/Permutations.java: -------------------------------------------------------------------------------- 1 | package backtracking; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | /** 7 | * Created by gouthamvidyapradhan on 15/03/2017. 8 | * Given a collection of distinct numbers, return all possible permutations. 9 | *

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> 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 list = new ArrayList<>(); 42 | for (int n : nums) 43 | list.add(n); 44 | result.add(list); 45 | } else { 46 | for (int j = i, l = nums.length; j < l; j++) { 47 | int temp = nums[j]; 48 | nums[j] = nums[i]; 49 | nums[i] = temp; 50 | nextPermutation(i + 1, nums, result); 51 | temp = nums[j]; 52 | nums[j] = nums[i]; 53 | nums[i] = temp; 54 | } 55 | } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /problems/src/linked_list/ReverseLinkedList.java: -------------------------------------------------------------------------------- 1 | package linked_list; 2 | 3 | /** 4 | * Created by gouthamvidyapradhan on 24/02/2017. 5 | * Reverse a singly linked list. 6 | */ 7 | public class ReverseLinkedList { 8 | private ListNode newHead; 9 | 10 | public static class ListNode { 11 | int val; 12 | ListNode next; 13 | 14 | ListNode(int x) { 15 | val = x; 16 | next = null; 17 | } 18 | } 19 | 20 | /** 21 | * Main method 22 | * 23 | * @param args 24 | * @throws Exception 25 | */ 26 | public static void main(String[] args) throws Exception { 27 | ListNode node1 = new ListNode(1); 28 | ListNode node2 = new ListNode(2); 29 | ListNode node3 = new ListNode(3); 30 | ListNode node4 = new ListNode(4); 31 | ListNode node5 = new ListNode(5); 32 | ListNode node6 = new ListNode(6); 33 | node1.next = node2; 34 | node2.next = node3; 35 | node3.next = node4; 36 | node4.next = node5; 37 | //node5.next = node6; 38 | ListNode newNode = new ReverseLinkedList().reverseList(node1); 39 | System.out.println(newNode.val); 40 | } 41 | 42 | public ListNode reverseList(ListNode head) { 43 | if (head == null) return null; 44 | else if (head.next == null) return head; 45 | reverse(head).next = null; 46 | return newHead; 47 | } 48 | 49 | private ListNode reverse(ListNode head) { 50 | if (head.next == null) { 51 | newHead = head; 52 | return head; 53 | } 54 | ListNode node = reverse(head.next); 55 | node.next = head; 56 | return head; 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /problems/src/backtracking/SubsetsII.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 integers that might contain duplicates, nums, return all possible subsets. 10 | *

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> 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 newList = new ArrayList<>(result.get(j)); 49 | newList.add(nums[i]); 50 | result.add(newList); 51 | } 52 | start = newStart; 53 | } 54 | return result; 55 | } 56 | 57 | } 58 | -------------------------------------------------------------------------------- /problems/src/array/LargestNumberAtLeastTwice.java: -------------------------------------------------------------------------------- 1 | package array; 2 | 3 | /** 4 | * Created by gouthamvidyapradhan on 09/02/2018. 5 | * In a given integer array nums, there is always exactly one largest element. 6 | 7 | Find whether the largest element in the array is at least twice as much as every other number in the array. 8 | 9 | If it is, return the index of the largest element, otherwise return -1. 10 | 11 | Example 1: 12 | 13 | Input: nums = [3, 6, 1, 0] 14 | Output: 1 15 | Explanation: 6 is the largest integer, and for every other number in the array x, 16 | 6 is more than twice as big as x. The index of value 6 is 1, so we return 1. 17 | 18 | 19 | Example 2: 20 | 21 | Input: nums = [1, 2, 3, 4] 22 | Output: -1 23 | Explanation: 4 isn't at least as big as twice the value of 3, so we return -1. 24 | 25 | 26 | Note: 27 | 28 | nums will have a length in the range [1, 50]. 29 | Every nums[i] will be an integer in the range [0, 99]. 30 | */ 31 | public class LargestNumberAtLeastTwice { 32 | 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 int dominantIndex(int[] nums) { 43 | int index = 0, max = Integer.MIN_VALUE; 44 | for(int i = 0; i < nums.length; i ++){ 45 | if(nums[i] > max){ 46 | max = nums[i]; 47 | index = i; 48 | } 49 | } 50 | for(int i = 0; i < nums.length; i ++){ 51 | if(i == index) continue; 52 | if(((long)nums[i] * 2) > max){ 53 | return -1; 54 | } 55 | } 56 | return index; 57 | } 58 | 59 | } 60 | -------------------------------------------------------------------------------- /problems/src/array/SetMatrixZeroes.java: -------------------------------------------------------------------------------- 1 | package array; 2 | 3 | import java.util.HashSet; 4 | import java.util.Set; 5 | 6 | /** 7 | * Created by pradhang on 3/28/2017. 8 | * Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place. 9 | *

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 row = new HashSet<>(); 33 | Set col = new HashSet<>(); 34 | int m = matrix.length; 35 | int n = matrix[0].length; 36 | for (int i = 0; i < m; i++) { 37 | for (int j = 0; j < n; j++) { 38 | if (matrix[i][j] == 0) { 39 | row.add(i); 40 | col.add(j); 41 | } 42 | } 43 | } 44 | 45 | for (int r : row) { 46 | for (int j = 0; j < n; j++) { 47 | matrix[r][j] = 0; 48 | } 49 | } 50 | 51 | for (int c : col) { 52 | for (int i = 0; i < m; i++) { 53 | matrix[i][c] = 0; 54 | } 55 | } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /problems/src/tree/LowestCommonAncestorBST.java: -------------------------------------------------------------------------------- 1 | package tree; 2 | 3 | /** 4 | * Created by gouthamvidyapradhan on 09/03/2017. 5 | * Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST. 6 | *

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 MAP = new HashMap<>(); 25 | private int index = 0, totalLen = 0; 26 | 27 | /** 28 | * Main method 29 | * 30 | * @param args 31 | * @throws Exception 32 | */ 33 | public static void main(String[] args) throws Exception { 34 | int[] perorder = {7, -10, -4, 3, -1, 2, -8, 11}; 35 | int[] inorder = {-4, -10, 3, -1, 7, 11, -8, 2}; 36 | new PreorderToBT().buildTree(perorder, inorder); 37 | } 38 | 39 | public TreeNode buildTree(int[] preorder, int[] inorder) { 40 | for (int i = 0, l = inorder.length; i < l; i++) 41 | MAP.put(inorder[i], i); 42 | totalLen = preorder.length; 43 | return build(preorder, 0, inorder.length - 1); 44 | } 45 | 46 | private TreeNode build(int[] preorder, int s, int e) { 47 | if (s > e || index >= totalLen) return null; 48 | 49 | int n = preorder[index++]; 50 | int pos = MAP.get(n); 51 | 52 | TreeNode node = new TreeNode(n); 53 | if (s == e) return node; 54 | 55 | node.left = build(preorder, s, pos - 1); 56 | node.right = build(preorder, pos + 1, e); 57 | return node; 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /problems/src/tree/LCA.java: -------------------------------------------------------------------------------- 1 | package tree; 2 | 3 | /** 4 | * Created by gouthamvidyapradhan on 21/03/2017. 5 | * Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. 6 | *

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 MAP = new HashMap<>(); 19 | 20 | // METHOD SIGNATURE BEGINS, THIS METHOD IS REQUIRED 21 | public static int hasBalancedBrackets(String str) { 22 | if (str == null) return 1; 23 | 24 | MAP.put(')', '('); 25 | MAP.put('}', '{'); 26 | MAP.put('>', '<'); 27 | MAP.put(']', '['); 28 | 29 | Stack stack = new Stack<>(); 30 | for (int i = 0, l = str.length(); i < l; i++) { 31 | switch (str.charAt(i)) { 32 | case '(': 33 | case '{': 34 | case '[': 35 | case '<': 36 | stack.push(str.charAt(i)); 37 | break; 38 | 39 | case ')': 40 | case '}': 41 | case ']': 42 | case '>': 43 | if (stack.isEmpty()) return 0; 44 | char top = stack.pop(); 45 | if (top != MAP.get(str.charAt(i))) return 0; 46 | break; 47 | 48 | default: //ignore 49 | } 50 | } 51 | return stack.isEmpty() ? 1 : 0; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /problems/src/string/CountAndSay.java: -------------------------------------------------------------------------------- 1 | package string; 2 | 3 | /** 4 | * Created by gouthamvidyapradhan on 20/01/2018. 5 | * 6 | * The count-and-say sequence is the sequence of integers with the first five terms as following: 7 | 8 | 1. 1 9 | 2. 11 10 | 3. 21 11 | 4. 1211 12 | 5. 111221 13 | 1 is read off as "one 1" or 11. 14 | 11 is read off as "two 1s" or 21. 15 | 21 is read off as "one 2, then one 1" or 1211. 16 | Given an integer n, generate the nth term of the count-and-say sequence. 17 | 18 | Note: Each term of the sequence of integers will be represented as a string. 19 | 20 | Example 1: 21 | 22 | Input: 1 23 | Output: "1" 24 | Example 2: 25 | 26 | Input: 4 27 | Output: "1211" 28 | 29 | */ 30 | public class CountAndSay { 31 | 32 | /** 33 | * Main method 34 | * @param args 35 | */ 36 | public static void main(String[] args) throws Exception { 37 | System.out.println(new CountAndSay().countAndSay(4)); 38 | } 39 | 40 | public String countAndSay(int n) { 41 | String result = "1"; 42 | for(int i = 1; i < n; i ++){ 43 | int count = 1; 44 | char num = result.charAt(0); 45 | StringBuilder temp = new StringBuilder(); 46 | for(int j = 1, l = result.length(); j < l; j++){ 47 | if(result.charAt(j) == num){ 48 | count++; 49 | } else{ 50 | temp = temp.append(String.valueOf(count)).append(String.valueOf(num)); 51 | num = result.charAt(j); 52 | count = 1; 53 | } 54 | } 55 | temp = temp.append(String.valueOf(count)).append(String.valueOf(num)); 56 | result = temp.toString(); 57 | } 58 | return result; 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /problems/src/array/MaximumSwap.java: -------------------------------------------------------------------------------- 1 | package array; 2 | 3 | /** 4 | * Created by gouthamvidyapradhan on 10/12/2017. 5 | * Given a non-negative integer, you could swap two digits at most once to get the maximum valued number. Return the 6 | * maximum valued number you could get. 7 | 8 | Example 1: 9 | Input: 2736 10 | Output: 7236 11 | Explanation: Swap the number 2 and the number 7. 12 | Example 2: 13 | Input: 9973 14 | Output: 9973 15 | Explanation: No swap. 16 | Note: 17 | The given number is in the range [0, 108] 18 | 19 | Solution O(n): Create a array of digit index. Iterate through the digits starting from left and in each iteration 20 | check if there is any digit which is greater than the current digit and appearing after the current index, if found 21 | then swap and return the new integer. 22 | */ 23 | public class MaximumSwap { 24 | 25 | public static void main(String[] args) throws Exception{ 26 | System.out.println(new MaximumSwap().maximumSwap(2736)); 27 | } 28 | 29 | public int maximumSwap(int num) { 30 | int[] D = new int[10]; 31 | char[] A = String.valueOf(num).toCharArray(); 32 | for(int i = 0; i < A.length; i ++){ 33 | D[A[i] - '0'] = i; 34 | } 35 | 36 | boolean found = false; 37 | 38 | for(int i = 0; i < A.length; i ++){ 39 | int digit = A[i] - '0'; 40 | for(int j = 9; j > digit; j--){ 41 | if(D[j] > i){ 42 | char temp = A[i]; 43 | A[i] = (char)(j + '0'); 44 | A[D[j]] = temp; 45 | found = true; 46 | break; 47 | } 48 | } 49 | if(found) break; 50 | } 51 | 52 | return Integer.parseInt(String.valueOf(A)); 53 | } 54 | 55 | } 56 | -------------------------------------------------------------------------------- /problems/src/divide_and_conquer/KthLargestElementInAnArray.java: -------------------------------------------------------------------------------- 1 | package divide_and_conquer; 2 | 3 | /** 4 | * Created by gouthamvidyapradhan on 09/03/2017. 5 | * Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element. 6 | *

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 visited = new HashSet<>(); 11 | List list = new ArrayList<>(); 12 | 13 | class Movie { 14 | private int movieId; 15 | private float rating; 16 | private ArrayList similarMovies; 17 | 18 | public List getSimilarMovies() { 19 | return similarMovies; 20 | } 21 | } 22 | 23 | /** 24 | * Main method 25 | * 26 | * @param args 27 | * @throws Exception 28 | */ 29 | public static void main(String[] args) throws Exception { 30 | 31 | } 32 | 33 | public Set getMovieRecommendations(Movie movie, int N) { 34 | dfs(movie); 35 | Set result = new HashSet<>(); 36 | Comparator cmp = new Comparator() { 37 | @Override 38 | public int compare(Movie o1, Movie o2) { 39 | return Float.compare(o2.rating, o1.rating); 40 | } 41 | }; 42 | Collections.sort(list, cmp); 43 | 44 | if (list.size() < N) { 45 | result.addAll(list); 46 | return result; 47 | } 48 | 49 | for (int i = 0; i < N; i++) { 50 | result.add(list.get(i)); 51 | } 52 | 53 | return result; 54 | } 55 | 56 | private void dfs(Movie m) { 57 | visited.add(m.movieId); // mark this visited 58 | List movies = m.getSimilarMovies(); 59 | for (Movie mo : movies) { 60 | if (!visited.contains(mo.movieId)) { 61 | list.add(mo); 62 | dfs(mo); 63 | } 64 | } 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /problems/src/string/RepeatedSubstringPattern.java: -------------------------------------------------------------------------------- 1 | package string; 2 | 3 | /** 4 | * Created by gouthamvidyapradhan on 25/03/2017. 5 | * Given a non-empty string check if it can be constructed by taking a substring of it and appending multiple copies of the substring together. You may assume the given string consists of lowercase English letters only and its length will not exceed 10000. 6 | *

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 list = new ArrayList<>(); 34 | while (st.hasMoreTokens()) { 35 | list.add(st.nextToken()); 36 | } 37 | for (int i = 0, l = list.size(); i < l; i++) { 38 | String str = list.get(i); 39 | String newStr = new StringBuilder(str).reverse().toString(); 40 | list.set(i, newStr); 41 | } 42 | StringBuilder result = new StringBuilder(); 43 | for (String str : list) { 44 | result.append(str).append(" "); 45 | } 46 | return result.toString().trim(); 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /problems/src/depth_first_search/NumberOfIslands.java: -------------------------------------------------------------------------------- 1 | package depth_first_search; 2 | 3 | /** 4 | * Created by gouthamvidyapradhan on 09/03/2017. 5 | * Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. 6 | *

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> 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 subList; 52 | if (level >= result.size()) { 53 | subList = new LinkedList<>(); 54 | result.add(subList); 55 | } else subList = (LinkedList) result.get(level); 56 | if (level % 2 == 0) 57 | subList.addFirst(root.val); //add to right 58 | else subList.add(root.val); //add to left 59 | dfs(root.right, level + 1, result); 60 | dfs(root.left, level + 1, result); 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /problems/src/string/SimplifyPath.java: -------------------------------------------------------------------------------- 1 | package string; 2 | 3 | import java.util.ArrayDeque; 4 | import java.util.Deque; 5 | import java.util.StringTokenizer; 6 | 7 | /** 8 | * Created by gouthamvidyapradhan on 28/07/2017. 9 | *

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 dQueue = new ArrayDeque<>(); 37 | while (st.hasMoreTokens()) { 38 | String token = st.nextToken(); 39 | if (token.trim().equals("..")) { 40 | if (!dQueue.isEmpty()) 41 | dQueue.pop(); 42 | } else if (token.trim().equals(".")) { 43 | //ignore 44 | } else dQueue.push(token); 45 | } 46 | if (dQueue.isEmpty()) return "/"; 47 | StringBuilder finalStr = new StringBuilder(); 48 | while (!dQueue.isEmpty()) { 49 | finalStr.append("/").append(dQueue.removeLast()); 50 | } 51 | return finalStr.toString(); 52 | } 53 | 54 | 55 | } 56 | -------------------------------------------------------------------------------- /problems/src/dynamic_programming/MaximalSquare.java: -------------------------------------------------------------------------------- 1 | package dynamic_programming; 2 | 3 | /** 4 | * Created by gouthamvidyapradhan on 28/11/2017. 5 | * Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area. 6 | 7 | For example, given the following matrix: 8 | 9 | 1 0 1 0 0 10 | 1 0 1 1 1 11 | 1 1 1 1 1 12 | 1 0 0 1 0 13 | Return 4. 14 | 15 | Solution: O(n * m) time and space complexity. 16 | Calculate the max length of a square using DP(i, j) = min(DP[i - 1][j], DP[i][j - 1], DP[i - 1][j - 1]) + 1 17 | Return the square of the answer. 18 | */ 19 | public class MaximalSquare { 20 | /** 21 | * Main method 22 | * @param args 23 | */ 24 | public static void main(String[] args) { 25 | char[][] A = {{'1','0','1','0','0'}, {'1','0','1','1','1'}, {'1','1','1','1','1'}, {'1','0','0','1','0'}}; 26 | System.out.println(new MaximalSquare().maximalSquare(A)); 27 | } 28 | 29 | public int maximalSquare(char[][] matrix) { 30 | if(matrix.length == 0) return 0; 31 | int[][] dp = new int[matrix.length][matrix[0].length]; 32 | for(int i = 0; i < matrix.length; i ++){ 33 | for(int j = 0; j < matrix[0].length; j++){ 34 | if(j - 1 >= 0 && i - 1 >= 0){ 35 | if(matrix[i][j] == '1'){ 36 | dp[i][j] = Math.min(dp[i - 1][j], dp[i][j - 1]); 37 | dp[i][j] = Math.min(dp[i][j], dp[i - 1][j - 1]) + 1; 38 | } 39 | } else { 40 | dp[i][j] = matrix[i][j] == '1' ? 1 : 0; 41 | } 42 | } 43 | } 44 | int max = 0; 45 | for(int i = 0; i < dp.length; i++){ 46 | for(int j = 0; j < dp[0].length; j++){ 47 | max = Math.max(max, dp[i][j]); 48 | } 49 | } 50 | return max * max; 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /problems/src/math/RotateFunction.java: -------------------------------------------------------------------------------- 1 | package math; 2 | 3 | /** 4 | * Created by gouthamvidyapradhan on 18/03/2017. 5 | * Given an array of integers A and let n to be its length. 6 | *

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> 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 row, String s, List> result) { 38 | if (i == s.length()) { 39 | List list = new ArrayList<>(row); 40 | result.add(list); 41 | } else { 42 | for (int j = i, l = s.length(); j < l; j++) { 43 | String sbStr = s.substring(i, j + 1); 44 | if (isPalindrome(sbStr)) { 45 | row.add(sbStr); 46 | doNext(j + 1, row, s, result); 47 | row.remove(row.size() - 1); 48 | } 49 | } 50 | } 51 | } 52 | 53 | private boolean isPalindrome(String s) { 54 | int i = 0, j = s.length() - 1; 55 | while (i <= j) { 56 | if (s.charAt(i) != s.charAt(j)) 57 | return false; 58 | i++; 59 | j--; 60 | } 61 | return true; 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /problems/src/tree/SubtreeOfAnotherTree.java: -------------------------------------------------------------------------------- 1 | package tree; 2 | 3 | /** 4 | * Created by gouthamvidyapradhan on 07/07/2017. 5 | * Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with a subtree of s. A subtree of s is a tree consists of a node in s and all of this node's descendants. The tree s could also be considered as a subtree of itself. 6 | *

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 result = new BinaryTreeInorderTraversal().inorderTraversal(root); 44 | System.out.println(result); 45 | } 46 | 47 | public List inorderTraversal(TreeNode root) { 48 | Stack stack = new Stack<>(); 49 | TreeNode curr = root; 50 | List result = new ArrayList<>(); 51 | while (curr != null || !stack.isEmpty()) { 52 | while (curr != null) { 53 | stack.push(curr); 54 | curr = curr.left; 55 | } 56 | curr = stack.pop(); 57 | result.add(curr.val); 58 | curr = curr.right; 59 | } 60 | return result; 61 | } 62 | 63 | } 64 | -------------------------------------------------------------------------------- /problems/src/tree/ClosestBinarySearchTreeValue.java: -------------------------------------------------------------------------------- 1 | package tree; 2 | 3 | /** 4 | * Created by gouthamvidyapradhan on 10/05/2017. 5 | * Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target. 6 | *

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 result = new LetterPhoneNumber().letterCombinations("23"); 32 | result.forEach(System.out::println); 33 | } 34 | 35 | private List letterCombinations(String digits) { 36 | if (digits == null || digits.isEmpty() || digits.contains("1") || digits.contains("0")) 37 | return new ArrayList<>(); 38 | List prev = new ArrayList<>(); 39 | prev.add(""); 40 | for (int i = digits.length() - 1; i >= 0; i--) { 41 | String str = NUMBER_ALPHA[Integer.parseInt(String.valueOf(digits.charAt(i)))]; 42 | List newList = new ArrayList<>(); 43 | for (int j = 0, l = str.length(); j < l; j++) { 44 | for (String s : prev) { 45 | s = str.charAt(j) + s; 46 | newList.add(s); 47 | } 48 | } 49 | prev = newList; 50 | } 51 | return prev; 52 | } 53 | 54 | 55 | } 56 | -------------------------------------------------------------------------------- /problems/src/hashing/ContiguousArray.java: -------------------------------------------------------------------------------- 1 | package hashing; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | /** 7 | * Created by gouthamvidyapradhan on 16/12/2017. 8 | * Given a binary array, find the maximum length of a contiguous subarray with equal number of 0 and 1. 9 | 10 | Example 1: 11 | Input: [0,1] 12 | Output: 2 13 | Explanation: [0, 1] is the longest contiguous subarray with equal number of 0 and 1. 14 | Example 2: 15 | Input: [0,1,0] 16 | Output: 2 17 | Explanation: [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1. 18 | Note: The length of the given binary array will not exceed 50,000. 19 | 20 | Solution: O(n) keep a count variable and increment count when a 1 is found and decrement count when a 0 is found. 21 | Maintain a map of count and its corresponding index. if the count repeats itself then take the difference of the 22 | current index and the index saved in the map. Max of the difference is the answer. 23 | */ 24 | public class ContiguousArray { 25 | /** 26 | * Main method 27 | * @param args 28 | * @throws Exception 29 | */ 30 | public static void main(String[] args) throws Exception{ 31 | int[] A = {1, 1}; 32 | System.out.println(new ContiguousArray().findMaxLength(A)); 33 | } 34 | 35 | public int findMaxLength(int[] nums) { 36 | Map map = new HashMap<>(); 37 | int count = 0; 38 | int max = 0; 39 | for(int i = 0; i < nums.length; i ++){ 40 | if(nums[i] == 0){ 41 | count--; 42 | } else count++; 43 | if(count == 0){ 44 | max = Math.max(max, i + 1); 45 | } else { 46 | if(map.containsKey(count)){ 47 | int index = map.get(count); 48 | max = Math.max(max, i - index); 49 | } else{ 50 | map.put(count, i); 51 | } 52 | } 53 | } 54 | return max; 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /problems/src/dynamic_programming/BestTimeToBuyAndSellStocksWithFee.java: -------------------------------------------------------------------------------- 1 | package dynamic_programming; 2 | 3 | /** 4 | * Created by gouthamvidyapradhan on 14/12/2017. 5 | * Your are given an array of integers prices, for which the i-th element is the price of a given stock on day i; 6 | * and a non-negative integer fee representing a transaction fee. 7 | 8 | You may complete as many transactions as you like, but you need to pay the transaction fee for each transaction. 9 | You may not buy more than 1 share of a stock at a time (ie. you must sell the stock share before you buy again.) 10 | 11 | Return the maximum profit you can make. 12 | 13 | Example 1: 14 | Input: prices = [1, 3, 2, 8, 4, 9], fee = 2 15 | Output: 8 16 | Explanation: The maximum profit can be achieved by: 17 | Buying at prices[0] = 1 18 | Selling at prices[3] = 8 19 | Buying at prices[4] = 4 20 | Selling at prices[5] = 9 21 | The total profit is ((8 - 1) - 2) + ((9 - 4) - 2) = 8. 22 | Note: 23 | 24 | 0 < prices.length <= 50000. 25 | 0 < prices[i] < 50000. 26 | 0 <= fee < 50000. 27 | 28 | Solution: O(n) for every step either you can buy stock or sell. Maintain two variables 'cash' to save max value if 29 | you had sold the stock at current price and 'stock' to save max value if you had purchased the stock at current 30 | price. Return max cash 31 | 32 | */ 33 | public class BestTimeToBuyAndSellStocksWithFee { 34 | 35 | /** 36 | * Main method 37 | * @param args 38 | * @throws Exception 39 | */ 40 | public static void main(String[] args) throws Exception{ 41 | int[] A = {1, 3, 2, 8, 4, 9}; 42 | System.out.println(new BestTimeToBuyAndSellStocksWithFee().maxProfit(A, 2)); 43 | } 44 | 45 | public int maxProfit(int[] prices, int fee) { 46 | int cash = 0, stock = -prices[0]; 47 | for(int i = 1; i < prices.length; i ++){ 48 | cash = Math.max(cash, prices[i] + stock - fee); 49 | stock = Math.max(stock, cash - prices[i]); 50 | } 51 | return cash; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /problems/src/hashing/TwoSum.java: -------------------------------------------------------------------------------- 1 | package hashing; 2 | 3 | import java.util.HashMap; 4 | 5 | /** 6 | * Created by gouthamvidyapradhan on 09/03/2017. 7 | * Given an array of integers, return indices of the two numbers such that they add up to a specific target. 8 | *

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 map = new HashMap<>(); 19 | 20 | public int[] twoSum(int[] nums, int target) { 21 | int[] result = new int[2]; 22 | 23 | for (int i : nums) { 24 | if (map.keySet().contains(i)) { 25 | int count = map.get(i); 26 | map.put(i, ++count); 27 | } else { 28 | map.put(i, 1); 29 | } 30 | } 31 | 32 | for (int i = 0, l = nums.length; i < l; i++) { 33 | int ele = nums[i]; 34 | int req = target - ele; 35 | if (map.keySet().contains(req)) { 36 | result[0] = i; 37 | if (ele == req) { 38 | int count = map.get(req); 39 | if (count > 1) { 40 | for (int j = i + 1; j < l; j++) { 41 | if (nums[j] == req) { 42 | result[1] = j; 43 | return result; 44 | } 45 | } 46 | } 47 | } else { 48 | for (int j = i + 1; j < l; j++) { 49 | if (nums[j] == req) { 50 | result[1] = j; 51 | return result; 52 | } 53 | } 54 | } 55 | } 56 | } 57 | return result; 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /problems/src/array/ThirdMaximumNumber.java: -------------------------------------------------------------------------------- 1 | package array; 2 | 3 | /** 4 | * Created by gouthamvidyapradhan on 25/03/2017. 5 | * Given a non-empty array of integers, return the third maximum number in this array. If it does not exist, return the maximum number. The time complexity must be in O(n). 6 | *

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 index = new HashMap<>(); 39 | int sum = 0; 40 | for(int i = 0; i < nums.length; i ++){ 41 | sum += nums[i]; 42 | index.putIfAbsent(sum, i); 43 | } 44 | sum = 0; 45 | int ans = 0; 46 | for(int i = 0; i < nums.length; i ++){ 47 | sum += nums[i]; 48 | if(sum == k){ 49 | ans = Math.max(ans, i + 1); 50 | } else{ 51 | int exp = sum - k; 52 | if(index.containsKey(exp)){ 53 | int farLeft = index.get(exp); 54 | if(farLeft < i){ 55 | ans = Math.max(ans, i - index.get(exp)); 56 | } 57 | } 58 | } 59 | } 60 | return ans; 61 | } 62 | 63 | } 64 | -------------------------------------------------------------------------------- /problems/src/array/SubarraySumEqualsK.java: -------------------------------------------------------------------------------- 1 | package array; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | /** 7 | * Created by gouthamvidyapradhan on 03/01/2018. 8 | * Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum 9 | * equals to k. 10 | 11 | Example 1: 12 | Input:nums = [1,1,1], k = 2 13 | Output: 2 14 | Note: 15 | The length of the array is in range [1, 20,000]. 16 | The range of numbers in the array is [-1000, 1000] and the range of the integer k is [-1e7, 1e7]. 17 | 18 | Solution: O(n) Maintain a hash-map of prefix sum and its count and check for range sum for each element. 19 | */ 20 | public class SubarraySumEqualsK { 21 | 22 | /** 23 | * Main method 24 | * @param args 25 | * @throws Exception 26 | */ 27 | public static void main(String[] args) throws Exception{ 28 | int[] A = {1, 2, 1, -2, 3, -1, -1}; 29 | System.out.println(new SubarraySumEqualsK().subarraySum(A, 2)); 30 | } 31 | 32 | public int subarraySum(int[] nums, int k) { 33 | Map map = new HashMap<>(); 34 | int sum = 0; 35 | for(int i : nums){ 36 | sum += i; 37 | Integer count = map.get(sum); 38 | if(count == null){ 39 | map.put(sum, 1); 40 | } else{ 41 | map.put(sum, count + 1); 42 | } 43 | } 44 | sum = 0; 45 | int result = 0; 46 | for(int i : nums){ 47 | int key = sum + k; 48 | if(map.containsKey(key)){ 49 | int count = map.get(key); 50 | result += count; 51 | } 52 | sum += i; 53 | if(map.containsKey(sum)){ 54 | int count = map.get(sum); 55 | if(count - 1 > 0){ 56 | map.put(sum, count - 1); 57 | } else{ 58 | map.remove(sum); 59 | } 60 | } 61 | } 62 | return result; 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /problems/src/dynamic_programming/CoinChange2.java: -------------------------------------------------------------------------------- 1 | package dynamic_programming; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | * Created by gouthamvidyapradhan on 22/03/2017. 7 | * You are given coins of different denominations and a total amount of money. Write a function to compute the number of combinations that make up that amount. You may assume that you have infinite number of each kind of coin. 8 | *

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> 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 row, 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 | *

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> 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 | *

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> result = new CombinationSum().combinationSum(candidates, 7); 33 | } 34 | 35 | public List> combinationSum(int[] candidates, int target) { 36 | List> result = new ArrayList<>(); 37 | List subList = new ArrayList<>(); 38 | doNext(0, result, 0, candidates, target, subList); 39 | return result; 40 | } 41 | 42 | private void doNext(int i, List> result, int count, int[] candidates, int target, List subArr) { 43 | if (target == 0) { 44 | List subList = new ArrayList<>(); 45 | for (int k = 0; k < count; k++) 46 | subList.add(subArr.get(k)); 47 | result.add(subList); 48 | } else if (target > 0) { 49 | for (int j = i, l = candidates.length; j < l; j++) { 50 | subArr.add(candidates[j]); 51 | doNext(j, result, count + 1, candidates, target - candidates[j], subArr); 52 | subArr.remove(subArr.size() - 1); 53 | } 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /problems/src/array/ImageSmoother.java: -------------------------------------------------------------------------------- 1 | package array; 2 | /** 3 | * Created by gouthamvidyapradhan on 17/02/2018. 4 | * * Given a 2D integer matrix M representing the gray scale of an image, you need to design a smoother to make the 5 | * gray scale of each cell becomes the average gray scale (rounding down) of all the 8 surrounding cells and itself. 6 | * If a cell has less than 8 surrounding cells, then use as many as you can. 7 | 8 | Example 1: 9 | Input: 10 | [[1,1,1], 11 | [1,0,1], 12 | [1,1,1]] 13 | Output: 14 | [[0, 0, 0], 15 | [0, 0, 0], 16 | [0, 0, 0]] 17 | Explanation: 18 | For the point (0,0), (0,2), (2,0), (2,2): floor(3/4) = floor(0.75) = 0 19 | For the point (0,1), (1,0), (1,2), (2,1): floor(5/6) = floor(0.83333333) = 0 20 | For the point (1,1): floor(8/9) = floor(0.88888889) = 0 21 | Note: 22 | The value in the given matrix is in the range of [0, 255]. 23 | The length and width of the given matrix are in the range of [1, 150]. 24 | */ 25 | 26 | public class ImageSmoother { 27 | 28 | int[] R = {1, -1, 0, 0, 1, -1, 1, -1}; 29 | int[] C = {0, 0, -1, 1, 1, 1, -1, -1}; 30 | public static void main(String[] args) throws Exception{ 31 | 32 | } 33 | 34 | public int[][] imageSmoother(int[][] M) { 35 | int[][] result = new int[M.length][M[0].length]; 36 | for(int i = 0; i < M.length; i ++){ 37 | for(int j = 0; j < M[0].length; j ++){ 38 | int numCount = 0; 39 | int totalCount = 1; 40 | for(int k = 0; k < 8; k++){ 41 | int newR = i + R[k]; 42 | int newC = j + C[k]; 43 | if(newR >= 0 && newC >= 0 && newR < M.length && newC < M[0].length){ 44 | if(M[newR][newC] > 0){ 45 | numCount += M[newR][newC]; 46 | } 47 | totalCount++; 48 | } 49 | } 50 | if(M[i][j] == 1) numCount++; 51 | result[i][j] = numCount / totalCount; 52 | } 53 | } 54 | return result; 55 | } 56 | 57 | } 58 | -------------------------------------------------------------------------------- /problems/src/dynamic_programming/ContinuousSubarraySum.java: -------------------------------------------------------------------------------- 1 | package dynamic_programming; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | /** 7 | * Created by gouthamvidyapradhan on 10/12/2017. 8 | * Given a list of non-negative numbers and a target integer k, write a function to check if the array has a 9 | * continuous subarray of size at least 2 that sums up to the multiple of k, that is, sums up to n*k where n is also 10 | * an integer. 11 | 12 | Example 1: 13 | Input: [23, 2, 4, 6, 7], k=6 14 | Output: True 15 | Explanation: Because [2, 4] is a continuous subarray of size 2 and sums up to 6. 16 | Example 2: 17 | Input: [23, 2, 6, 4, 7], k=6 18 | Output: True 19 | Explanation: Because [23, 2, 6, 4, 7] is an continuous subarray of size 5 and sums up to 42. 20 | Note: 21 | The length of the array won't exceed 10,000. 22 | You may assume the sum of all the numbers is in the range of a signed 32-bit integer. 23 | 24 | Solution: O(n) sum the elements and maintain a hashmap of key value pair of (sum % k) -> index. If the key is 25 | already found in the hashmap and the difference in the current_index and hashmap index is > 1 then return true. 26 | */ 27 | public class ContinuousSubarraySum { 28 | 29 | /** 30 | * Main method 31 | * @param args 32 | */ 33 | public static void main(String[] args) throws Exception{ 34 | int[] A = {1, 3, 6, 12, 7}; 35 | System.out.println(new ContinuousSubarraySum().checkSubarraySum(A, 6)); 36 | } 37 | 38 | public boolean checkSubarraySum(int[] nums, int k) { 39 | Map map = new HashMap<>(); 40 | int sum = 0; 41 | map.put(0, -1); 42 | for(int i = 0; i < nums.length; i ++){ 43 | sum += nums[i]; 44 | int mod = (k == 0) ? sum : sum % k; //this is to handle case where k is 0 45 | if(map.containsKey(mod)){ 46 | if(i - map.get(mod) > 1){ 47 | return true; 48 | } 49 | } else{ 50 | map.put(mod, i); 51 | } 52 | } 53 | return false; 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /problems/src/two_pointers/ThreeSumClosest.java: -------------------------------------------------------------------------------- 1 | package two_pointers; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | * Created by gouthamvidyapradhan on 13/06/2017. 7 | * Accepted 8 | * Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution. 9 | *

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 stack = new Stack<>(); 34 | 35 | /** 36 | * Main method 37 | * 38 | * @param args 39 | * @throws Exception 40 | */ 41 | public static void main(String[] args) throws Exception { 42 | MinStack minStack = new MinStack(); 43 | minStack.push(-2); 44 | minStack.push(0); 45 | minStack.push(-3); 46 | System.out.println(minStack.getMin()); 47 | minStack.pop(); 48 | System.out.println(minStack.top()); 49 | System.out.println(minStack.getMin()); 50 | } 51 | 52 | public MinStack() { 53 | 54 | } 55 | 56 | public void push(int x) { 57 | Node node; 58 | if (!stack.isEmpty()) { 59 | Node top = stack.peek(); 60 | node = new Node(x, Math.min(top.min, x)); 61 | } else { 62 | node = new Node(x, x); 63 | } 64 | stack.push(node); 65 | } 66 | 67 | public void pop() { 68 | stack.pop(); 69 | } 70 | 71 | public int top() { 72 | return stack.peek().value; 73 | } 74 | 75 | public int getMin() { 76 | return stack.peek().min; 77 | } 78 | 79 | } 80 | -------------------------------------------------------------------------------- /problems/src/string/StringToInteger.java: -------------------------------------------------------------------------------- 1 | package string; 2 | 3 | /** 4 | * Created by gouthamvidyapradhan on 21/03/2017. 5 | * Implement atoi to convert a string to an integer. 6 | *

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 list = new ArrayList<>(); 33 | 34 | /** 35 | * Main method 36 | * 37 | * @param args 38 | * @throws Exception 39 | */ 40 | public static void main(String[] args) throws Exception { 41 | TreeNode root = new TreeNode(2); 42 | root.left = new TreeNode(3); 43 | root.right = new TreeNode(4); 44 | root.right.right = new TreeNode(5); 45 | root.right.left = new TreeNode(4); 46 | root.right.left.right = new TreeNode(8); 47 | root.right.left.left = new TreeNode(7); 48 | root.right.left.left.right = new TreeNode(10); 49 | root.right.left.left.left = new TreeNode(7); 50 | 51 | List list = new BinarayTreeRightSideView().rightSideView(root); 52 | } 53 | 54 | public List rightSideView(TreeNode root) { 55 | if (root == null) return list; 56 | dfs(root, 0); 57 | return list; 58 | } 59 | 60 | private void dfs(TreeNode node, int height) { 61 | if (node != null) { 62 | if (height > maxHeigh) { 63 | list.add(node.val); 64 | maxHeigh = height; 65 | } 66 | dfs(node.right, height + 1); 67 | dfs(node.left, height + 1); 68 | } 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /problems/src/tree/BinaryTreeMaximumPathSum.java: -------------------------------------------------------------------------------- 1 | package tree; 2 | 3 | /** 4 | * Created by gouthamvidyapradhan on 03/04/2017. 5 | * Given a binary tree, find the maximum path sum. 6 | *

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 | --------------------------------------------------------------------------------