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
34 changes: 34 additions & 0 deletions kdiffPairs.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// Time Complexity : O(n).
// Space Complexity : O(n)
// Did this code successfully run on Leetcode : Yes
// Approach : Maintaining a HashMap with frequencies and iterating over the hashmap to find the complement helps in finding the k diff
// pairs as only unique values are allowed. Only special case is for k=0, for which we need to consider the keys that have more than 2 as their frequency.

class Solution {
public int findPairs(int[] nums, int k) {
HashMap<Integer, Integer> map = new HashMap<>();
int count = 0;
for(int num : nums){ //store in hashmap
if(map.containsKey(num)){
map.put(num, map.get(num)+1);
} else{
map.put(num, 1);
}
}


for(int num : map.keySet()){
if(k>0){ //search for complement in hashmap
if(map.containsKey(num - k)){
count++;
}
}
else if(k==0){ //checking frequencies for k=0 and we need same key pairs
if(map.get(num) >= 2){
count++;
}
}
}
return count;
}
}
27 changes: 27 additions & 0 deletions pascalTriangle.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
// Time Complexity : O(n).
// Space Complexity : O(n)
// Did this code successfully run on Leetcode : Yes
// Approach : We can construct a row from previous row by adding index and index-1 of previous row for a index in current row.
// And append 1 at both the ends of the row. As the output is expected in List<List<Integer>>, we perform operations on the List.


class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> result = new ArrayList<>();
if(numRows >= 1){
result.add(new ArrayList<>(Arrays.asList(1))); // first row is always [1]
}
for(int i=1;i<numRows;i++){
List<Integer> curr = new ArrayList<>();
List<Integer> prev = new ArrayList<>();
prev = result.get(i-1);
curr.add(1); //first elements is always 1
for(int j=1;j<prev.size();j++){
curr.add(prev.get(j)+prev.get(j-1)); //previous row's index sum
}
curr.add(1);//last element is always 1
result.add(curr);
}
return result;
}
}