Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions ContiguousSubarray.java
Original file line number Diff line number Diff line change
@@ -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<Integer, Integer> 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;
}
}
33 changes: 33 additions & 0 deletions LongestPalindrome.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import java.util.*;

// O(n) time, O(1) space
class Solution {
public int longestPalindrome(String s) {
Map<Character, Integer> 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<Character, Integer> 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;
}
}
26 changes: 26 additions & 0 deletions SubarraySumEqualsK.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import java.util.*;

// O(n) time, O(n) space
class Solution {
public int subarraySum(int[] nums, int k) {

Map<Integer, Integer> 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;
}
}