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
37 changes: 37 additions & 0 deletions KDiffPairsInAnArray.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import java.util.HashMap;
import java.util.Map;

/**
* I took frequencyMap to maintain the count of occurences of a num in nums.
* I iterated on the frequencyMap to avoid finding repeated pairs.
* Considering the key as nums[i], I am looking for nums[j] which is equal to nums[i] - k.
* nums[j] can also be equal to nums[i] + k. But I'm not looking for it to avoid finding repeated pairs.
* When nums[i] - k is found I am increasing the result by 1.
* When k = 0, I need look for repeated numbers since nums[i] - nums[j] = 0 => nums[i] = nums[j].
*/
// Time: N + N ~= O(N)
// Space: O(N) for frequencyMap
class Solution {
public int findPairs(int[] nums, int k) {
Map<Integer, Integer> frequencyMap = new HashMap<>();
// Populate map
for (int num: nums) {
frequencyMap.put(num, frequencyMap.getOrDefault(num, 0) + 1);
}
int numOfPairs = 0;
// Iterate through key set of the map
for (Map.Entry<Integer, Integer> entry: frequencyMap.entrySet()) {
if (k != 0) {
if (frequencyMap.containsKey(entry.getKey() - k)) {
numOfPairs ++;
}
} else {
// As k = 0, look for repeated number
if (entry.getValue() >= 2) {
numOfPairs ++;
}
}
}
return numOfPairs;
}
}
33 changes: 33 additions & 0 deletions PascalsTriangle.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
* I initalized the first row and second row.
* Iterated through each index of the next rows. Initialized values first and last indices of each row as 1.
* Calculated the remaining values using the formula triangle.get(rowNum - 1).get(index - 1) + triangle.get(rowNum - 1).get(index)
*/
// Time: O(N * (N + 1) / 2) ~= O(N^2); where N = numRows
// Space: O(N) for currentRow inside for loop
class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> triangle = new ArrayList<>();
triangle.add(Arrays.asList(1)); // first row
if (numRows == 1) {
return triangle;
}
triangle.add(Arrays.asList(1, 1)); // second row
// Iterate from third row to the end
for (int rowNum = 2; rowNum < numRows; rowNum ++) {
List<Integer> currentRow = new ArrayList<>();
currentRow.add(1); // first element
for (int index = 1; index < rowNum; index ++) {
currentRow.add(index,
triangle.get(rowNum - 1).get(index - 1) + triangle.get(rowNum - 1).get(index));
}
currentRow.add(1); // last element
triangle.add(currentRow);
}
return triangle;
}
}