diff --git a/ContiguousSubarray.java b/ContiguousSubarray.java new file mode 100644 index 00000000..fc89596f --- /dev/null +++ b/ContiguousSubarray.java @@ -0,0 +1,30 @@ +import java.util.*; + +// O(n) time, O(n) space +class Solution { + public int findMaxLength(int[] nums) { + int n = nums.length; + int maxLen = 0; + int runninSum = 0; + + Map map = new HashMap<>(); + map.put(0, -1); // edge case when runningSum is 0 initially, should be at -1 idx + + for (int i = 0; i < n; i++) { + if (nums[i] == 0) { + runninSum--; + } + else { + runninSum++; + } + + if (map.containsKey(runninSum)) { + maxLen = Math.max(maxLen, i - map.get(runninSum)); + } + else { + map.put(runninSum, i); + } + } + return maxLen; + } +} \ No newline at end of file diff --git a/LongestPalindrome.java b/LongestPalindrome.java new file mode 100644 index 00000000..b5f982b2 --- /dev/null +++ b/LongestPalindrome.java @@ -0,0 +1,33 @@ +import java.util.*; + +// O(n) time, O(1) space +class Solution { + public int longestPalindrome(String s) { + Map map = new HashMap<>(); + + int count = 0; + boolean oddChar = false; + + for (int i = 0; i < s.length(); i++) { + char c = s.charAt(i); + + map.put(c, map.getOrDefault(c, 0) + 1); + } + + for (Map.Entry e : map.entrySet()) { + int freq = e.getValue(); + + if (freq % 2 == 0) { + count += freq; + } + else { + count += freq - 1; + oddChar = true; + } + } + if (oddChar) { + return count + 1; // can choose 1 of remaining odd chars to go in middle + } + return count; + } +} \ No newline at end of file diff --git a/SubarraySumEqualsK.java b/SubarraySumEqualsK.java new file mode 100644 index 00000000..b9c89f13 --- /dev/null +++ b/SubarraySumEqualsK.java @@ -0,0 +1,26 @@ +import java.util.*; + +// O(n) time, O(n) space +class Solution { + public int subarraySum(int[] nums, int k) { + + Map map = new HashMap<>(); + map.put(0, 1); // initially runningSum has freq of 1 + + int count = 0; + int runningSum = 0; + + for (int i = 0; i < nums.length; i++) { + runningSum += nums[i]; + + int complement = runningSum - k; + + if (map.containsKey(complement)) { + count += map.get(complement); + } + + map.put(runningSum, map.getOrDefault(runningSum, 0) + 1); + } + return count; + } +} \ No newline at end of file