diff --git a/ContiguousArray.java b/ContiguousArray.java new file mode 100644 index 00000000..9a1e1351 --- /dev/null +++ b/ContiguousArray.java @@ -0,0 +1,20 @@ +class ContiguousArray { + public int findMaxLength(int[] nums) { + + HashMap rSum = new HashMap<>(); + rSum.put(0, -1); + int sum = 0, max = 0; + for(int i = 0; i < nums.length; i++) { + sum += nums[i] == 0 ? -1 : 1; + + if(rSum.containsKey(sum)) { + max = Math.max(max, i - rSum.get(sum)); + } else { + rSum.put(sum, i); + } + } + + return max; + + } +} \ No newline at end of file diff --git a/LongestPalindrome.java b/LongestPalindrome.java new file mode 100644 index 00000000..91eb48e2 --- /dev/null +++ b/LongestPalindrome.java @@ -0,0 +1,18 @@ +class LongestPalindrome { + public int longestPalindrome(String s) { + + Set dict = new HashSet<>(); + int count = 0; + + for(char c : s.toCharArray()) { + if(dict.contains(c)) { + count += 2; + dict.remove(c); + } else { + dict.add(c); + } + } + + return dict.size() > 0 ? count + 1 : count; + } +} \ No newline at end of file diff --git a/README.md b/README.md index 039a4259..2c1ad367 100644 --- a/README.md +++ b/README.md @@ -3,10 +3,10 @@ Explain your approach in **three sentences only** at top of your code -## Problem1 (https://leetcode.com/problems/subarray-sum-equals-k/) +## Problem1 SubArraySum (https://leetcode.com/problems/subarray-sum-equals-k/) -## Problem2 (https://leetcode.com/problems/contiguous-array/) +## Problem2 ContiguousArray (https://leetcode.com/problems/contiguous-array/) -## Problem3 (https://leetcode.com/problems/longest-palindrome) +## Problem3 LongestPalindrome (https://leetcode.com/problems/longest-palindrome) diff --git a/SubArraySum.java b/SubArraySum.java new file mode 100644 index 00000000..a3a5745d --- /dev/null +++ b/SubArraySum.java @@ -0,0 +1,21 @@ +// Using RSum to calculate the sum at that Index +// Add a default entry in the map with [0, 1] to make sure if the comp(rSum -k) is 0 then the array until that elemnt will be 1 sub array +// if different between running sum to k is available in the map then a sub array is found +// insert element in the map based on running sum and counter +class SubArraySum { + public int subarraySum(int[] nums, int k) { + HashMap rSumCounterMap = new HashMap<>(); + int rSum = 0; + rSumCounterMap.put(0, 1); + int count = 0; + for(int i = 0; i< nums.length;i++) { + rSum += nums[i]; + + if(rSumCounterMap.containsKey(rSum - k)) { + count += rSumCounterMap.get(rSum - k); + } + rSumCounterMap.merge(rSum, 1, Integer::sum); + } + return count; + } +} \ No newline at end of file