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
43 changes: 43 additions & 0 deletions KDiffPairs.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
// Time Complexity : O(n) + O(n) ~ O(n) where n is the number of elements
// Space Complexity : O(n)
// Did this code successfully run on Leetcode : Yes
// Any problem you faced while coding this : Yes, was not able to come up with the solution in the mock interview


// Your code here along with comments explaining your approach
/*
I first counted the number of all the occurences of the numbers. The reason why I counted first is because the 2nd number might be encounter later than the first.
The formula nums[i] - nums[j] == k is equivalent to nums[j] = nums[i] - k. So if k > 0, we will find the nums[i] - k in the hashmap, if we find it which means the pair satisfies the condition and increment the count.
One thing to note is that if k == 0, then if the number of occurences is greater than 2, it means we found a pair and increment the count.
*/

import java.util.HashMap;
import java.util.Map;

public class KDiffPairs {
public int findPairs(int[] nums, int k) {
HashMap<Integer, Integer> hmap = new HashMap<>();
int res = 0;

for(int num : nums) {
hmap.put(num, hmap.getOrDefault(num, 0) + 1);
}

for(Map.Entry<Integer,Integer> entry : hmap.entrySet()) {
int key = entry.getKey();
int val = entry.getValue();

if(k == 0) {
if(val > 1) {
res++;
}
} else {
if(hmap.containsKey(key + k)) {
res++;
}
}
}

return res;
}
}
37 changes: 37 additions & 0 deletions PascalTriange.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
// Time Complexity : O(n^2) where n is the numRows
// Space Complexity : O(n)
// Did this code successfully run on Leetcode : Yes
// Any problem you faced while coding this : No


// Your code here along with comments explaining your approach
/*
I first stored the initial array of [[1]] in the result.
I then started from row = 1 and then used the formula res[i-1][j-1] + res[i-1][j] to calculate the remaining columns.
*/


import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class PascalTriange {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> res = new ArrayList<>();
res.add(new ArrayList<>(Arrays.asList(1)));

for(int i = 1;i<numRows;i++) {
List<Integer> temp = new ArrayList<>();
for(int j = 0;j<=i;j++){
if(j == 0 || j == i) {
temp.add(1);
} else {
temp.add(res.get(i-1).get(j-1) + res.get(i-1).get(j));
}
}
res.add(temp);
}

return res;
}
}