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
28 changes: 28 additions & 0 deletions Subarray sum equals k.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
// TimeComplexity: O(n)
// SpaceComplexity: O(n)
// Did this code successfully run on Leetcode : yes
// Three sentences abou the solution: We count the number of subarrays whose sum equals k using a prefix-sum approach.It keeps a running sum and uses a HashMap to store how many times each prefix sum has occurred.
// If (currentSum − k) exists in the map, it means a subarray ending at the current index sums to k.
// The map is updated at each step with the current prefix sum count. Finally, we return the total number of such subarrays found.

class Solution {
public int subarraySum(int[] nums, int k) {
int count =0;
int sum =0;
HashMap<Integer,Integer> map = new HashMap<>();
map.put(0,1);
for(int i=0; i<nums.length; i++){
sum = sum +nums[i];
if(map.containsKey(sum-k)) {
int val = map.get(sum-k);
count = count +val;
}
if(map.containsKey(sum)) {
map.put(sum, map.get(sum) +1);
} else {
map.put(sum,1);
}
}
return count;
}
}
24 changes: 24 additions & 0 deletions contiguous array.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
// TimeComplexity: O(n)
// SpaceComplexity: O(n)
// Did this code successfully run on Leetcode : yes
// Any problem you faced while coding this : no

class Solution {
public int findMaxLength(int[] nums) {
int max = 0;
int sum = 0;
HashMap<Integer, Integer> map = new HashMap<>();
map.put(0,-1);
for(int i=0; i<nums.length; i++) {
sum = nums[i] == 0 ? sum-1 :sum+1;
if(map.containsKey(sum)) {
int curr = i - map.get(sum);
max = Math.max(max,curr);

} else {
map.put(sum,i);
}
}
return max;
}
}
24 changes: 24 additions & 0 deletions longest palindrome.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
// TimeComplexity: O(n)
// SpaceComplexity: O(n)
// Did this code successfully run on Leetcode : yes
// Any problem you faced while coding this : no

class Solution {
public int longestPalindrome(String s) {
HashSet<Character> set = new HashSet<>();
int count =0;
for(int i=0; i<s.length(); i++) {
char ch = s.charAt(i);
if(set.contains(ch)){
count =count+2;
set.remove(ch);
} else{
set.add(ch);
}
}
if(!set.isEmpty()){
count=count+1;
}
return count;
}
}