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
42 changes: 42 additions & 0 deletions KDiffPairs.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
// Time Complexity : O(N)
// Space Complexity : O(N), extra hashmap used
// Did this code successfully run on Leetcode : Yes
// Any problem you faced while coding this : No

// Approach
// Since we need unique pair, we dont want any value to be considered multiple times, causing duplicate pairs.
// Need to handle edge case if k=0, then that occurs 2 or more times should be considered a pair.
// We will keep a frequency map, go over each key, try to find if there exists key-K value in the map, if yes, increase
// the result count.
import java.util.HashMap;
import java.util.Map;

public class KDiffPairs {

public int findPairs(int[] nums, int k) {
// Frequency map makes sure a value is not part of multiple pairs
Map<Integer, Integer> temp = new HashMap<>();
int count = 0;
for(int num: nums){
if(temp.containsKey(num)){
temp.put(num, temp.get(num)+1);
}else {
temp.put(num, 1);
}
// temp.merge(num, 1, Integer::sum);
}

for(int key: temp.keySet()){
if(k==0){
// If no difference, then the same value can create a pair if it has occurred 2 or more times.
if(temp.get(key) > 1){
count++;
}
}else if(temp.containsKey(key-k)){
count++;
}
}

return count;
}
}
44 changes: 44 additions & 0 deletions PascalTriangle.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
// Time Complexity : O(NXN), where N is number of rows
// Space Complexity : O(1)
// Did this code successfully run on Leetcode : Yes
// Any problem you faced while coding this : No

// Approach
// One approach is we can add 1 to beginning and ending of each row to avoid going beyond the boundaries.
// Second approach check if i/j is beyond boundary, dont fetch them just use 0 and add it to [i-1],[j] value.

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

public class PascalTriangle {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> result = new ArrayList<>();
if(numRows == 0) return result;
// create first row
result.add(List.of(1));

for (int i = 1; i < numRows; i++) {
List<Integer> temp = new ArrayList<>();
for (int j = 0; j < numRows; j++) {
int top = 0;
// Check if [i-1][j] value exist by comparing j and size of previous row. Else use 0.
if (j < result.get(i-1).size()) {
top = result.get(i - 1).get(j);
}
int topLeft = 0;
// Check if [i-1][j-1] value exists, this will fail when j is at the boundary, j==0. Else use 0.
if (j > 0) {
topLeft = result.get(i - 1).get(j - 1);
}
temp.add(top + topLeft);
// As soon as required number of elements are processes break.
if(j == i){
break;
}
}
result.add(temp);
}

return result;
}
}