Skip to content

Commit a293914

Browse files
committed
Update
1 parent 6bc849e commit a293914

13 files changed

+673
-7
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package binary_search;
2+
3+
/**
4+
* Description: https://leetcode.com/problems/find-minimum-in-rotated-sorted-array
5+
* Difficulty: Medium
6+
* Time complexity: O(log n)
7+
* Space complexity: O(1)
8+
*/
9+
public class FindMinimumInRotatedSortedArray {
10+
11+
public int findMin(int[] nums) {
12+
int left = 0;
13+
int right = nums.length - 1;
14+
15+
while (left < right) {
16+
int mid = left + (right - left) / 2;
17+
18+
if (nums[mid] > nums[right]) {
19+
left = mid + 1;
20+
} else {
21+
right = mid;
22+
}
23+
}
24+
25+
return nums[left];
26+
}
27+
}

src/binary_search/SearchInRotatedSortedArray.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ private int findPivot(int[] nums) {
2323
while (left < right) {
2424
int mid = (left + right) / 2;
2525

26-
if (nums[mid] >= nums[0]) {
26+
if (nums[mid] > nums[right]) {
2727
left = mid + 1;
2828
} else {
2929
right = mid;
Lines changed: 130 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,130 @@
1+
package graph;
2+
3+
import java.util.*;
4+
5+
/**
6+
* Description: https://leetcode.com/problems/pacific-atlantic-water-flow
7+
* Difficulty: Medium
8+
*/
9+
public class PacificAtlanticWaterFlow {
10+
11+
private int[][] directions;
12+
13+
/**
14+
* Time complexity: O(m * n)
15+
* Space complexity: O(m * n)
16+
*/
17+
public List<List<Integer>> pacificAtlanticOptimalApproach(int[][] heights) {
18+
directions = new int[][]{{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
19+
int[][] pacific = new int[heights.length][heights[0].length];
20+
int[][] atlantic = new int[heights.length][heights[0].length];
21+
22+
// start flow from left and right borders
23+
for (int i = 0; i < heights.length; i++) {
24+
dfs(heights, pacific, new int[]{i, 0});
25+
dfs(heights, atlantic, new int[]{i, heights.length - 1});
26+
}
27+
28+
// start flow from top and bottom borders
29+
for (int i = 0; i < heights[0].length; i++) {
30+
dfs(heights, pacific, new int[]{0, i});
31+
dfs(heights, atlantic, new int[]{heights[0].length - 1, i});
32+
}
33+
34+
// if cell was visited by both flows -> add to the result
35+
List<List<Integer>> result = new ArrayList<>();
36+
for (int i = 0; i < heights.length; i++) {
37+
for (int j = 0; j < heights[0].length; j++) {
38+
if (pacific[i][j] != 0 && atlantic[i][j] != 0) {
39+
result.add(List.of(i, j));
40+
}
41+
}
42+
}
43+
44+
return result;
45+
}
46+
47+
private void dfs(int[][] heights, int[][] visited, int[] start) {
48+
Deque<int[]> stack = new LinkedList<>();
49+
stack.push(start);
50+
51+
while (!stack.isEmpty()) {
52+
int[] current = stack.poll();
53+
54+
if (visited[current[0]][current[1]] == 0) {
55+
stack.push(current);
56+
visited[current[0]][current[1]] = 1;
57+
58+
for (int[] dir : directions) {
59+
int x = current[0] + dir[0];
60+
int y = current[1] + dir[1];
61+
62+
if (x >= 0 && y >= 0 && x < heights.length && y < heights[0].length
63+
&& visited[x][y] == 0
64+
// we're going backwards -> next height should be greater or equal than current
65+
&& heights[x][y] >= heights[current[0]][current[1]]) {
66+
stack.push(new int[]{x, y});
67+
}
68+
}
69+
} else if (visited[current[0]][current[1]] == 1) {
70+
visited[current[0]][current[1]] = 2;
71+
}
72+
}
73+
}
74+
75+
/**
76+
* Time complexity: O(m^2 * n^2)
77+
* Space complexity: O(m * n)
78+
*/
79+
public List<List<Integer>> pacificAtlanticNaiveApproach(int[][] heights) {
80+
directions = new int[][]{{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
81+
82+
List<List<Integer>> result = new ArrayList<>();
83+
for (int i = 0; i < heights.length; i++) {
84+
for (int j = 0; j < heights[0].length; j++) {
85+
if (canFlowBothWays(heights, new int[]{i, j})) {
86+
result.add(List.of(i, j));
87+
}
88+
}
89+
}
90+
91+
return result;
92+
}
93+
94+
private boolean canFlowBothWays(int[][] heights, int[] start) {
95+
int[][] visited = new int[heights.length][heights[0].length];
96+
boolean hasPacificPath = false;
97+
boolean hasAtlanticPath = false;
98+
99+
Deque<int[]> stack = new LinkedList<>();
100+
stack.push(start);
101+
102+
while (!stack.isEmpty()) {
103+
int[] current = stack.poll();
104+
105+
if (visited[current[0]][current[1]] == 0) {
106+
visited[current[0]][current[1]] = 1;
107+
stack.push(current);
108+
109+
for (int[] dir : directions) {
110+
int x = current[0] + dir[0];
111+
int y = current[1] + dir[1];
112+
113+
if (x < 0 || y < 0) {
114+
hasPacificPath = true;
115+
} else if (x >= heights.length || y >= heights[0].length) {
116+
hasAtlanticPath = true;
117+
} else if (visited[x][y] == 0 && heights[x][y] <= heights[current[0]][current[1]]) {
118+
stack.push(new int[]{x, y});
119+
}
120+
121+
if (hasPacificPath && hasAtlanticPath) return true;
122+
}
123+
} else if (visited[current[0]][current[1]] == 1) {
124+
visited[current[0]][current[1]] = 2;
125+
}
126+
}
127+
128+
return false;
129+
}
130+
}
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
package hash_table;
2+
3+
import java.util.*;
4+
5+
/**
6+
* Description: https://leetcode.com/problems/insert-delete-getrandom-o1
7+
* Difficulty: Medium
8+
* Time complexity: O(1)
9+
* Space complexity: O(n)
10+
*/
11+
public class InsertDeleteGetRandom {
12+
13+
private static class RandomizedSet {
14+
15+
private final List<Integer> values;
16+
private final Map<Integer, Integer> indicesMap;
17+
private final Random random;
18+
19+
public RandomizedSet() {
20+
values = new ArrayList<>();
21+
indicesMap = new HashMap<>();
22+
random = new Random();
23+
}
24+
25+
public boolean insert(int val) {
26+
if (indicesMap.containsKey(val)) return false;
27+
28+
values.add(val);
29+
indicesMap.put(val, values.size() - 1);
30+
31+
return true;
32+
}
33+
34+
public boolean remove(int val) {
35+
if (!indicesMap.containsKey(val)) return false;
36+
37+
int idx = indicesMap.get(val);
38+
int lastIdx = values.size() - 1;
39+
40+
if (idx != lastIdx) { // overwrite element to be removed with the last one
41+
int lastVal = values.get(lastIdx);
42+
values.set(idx, lastVal);
43+
indicesMap.put(lastVal, idx);
44+
}
45+
46+
values.remove(lastIdx); // remove the last element
47+
indicesMap.remove(val);
48+
49+
return true;
50+
}
51+
52+
public int getRandom() {
53+
int randomIdx = random.nextInt(values.size());
54+
return values.get(randomIdx);
55+
}
56+
}
57+
}
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
package hash_table;
2+
3+
import java.util.*;
4+
5+
/**
6+
* Description: https://leetcode.com/problems/insert-delete-getrandom-o1-duplicates-allowed
7+
* Difficulty: Hard
8+
* Time complexity: O(1)
9+
* Space complexity: O(n)
10+
*/
11+
public class InsertDeleteGetRandomDuplicatesAllowed {
12+
13+
private static class RandomizedCollection {
14+
15+
private final List<Integer> values;
16+
private final Map<Integer, Set<Integer>> indicesMap;
17+
private final Random random;
18+
19+
public RandomizedCollection() {
20+
values = new ArrayList<>();
21+
indicesMap = new HashMap<>();
22+
random = new Random();
23+
}
24+
25+
public boolean insert(int val) {
26+
values.add(val);
27+
Set<Integer> indices = indicesMap.computeIfAbsent(val, __ -> new HashSet<>());
28+
indices.add(values.size() - 1);
29+
30+
return indices.size() == 1;
31+
}
32+
33+
public boolean remove(int val) {
34+
Set<Integer> indices = indicesMap.getOrDefault(val, Set.of());
35+
if (indices.isEmpty()) return false;
36+
37+
int idx = indices.iterator().next();
38+
indices.remove(idx);
39+
40+
int lastIdx = values.size() - 1;
41+
42+
if (idx != lastIdx) { // overwrite element to be removed with the last one
43+
int lastVal = values.get(lastIdx);
44+
values.set(idx, lastVal);
45+
46+
Set<Integer> lastValIndices = indicesMap.get(lastVal);
47+
lastValIndices.remove(lastIdx);
48+
lastValIndices.add(idx);
49+
}
50+
51+
values.remove(lastIdx); // remove the last element
52+
if (indices.isEmpty()) indicesMap.remove(val);
53+
54+
return true;
55+
}
56+
57+
public int getRandom() {
58+
int randomIdx = random.nextInt(values.size());
59+
return values.get(randomIdx);
60+
}
61+
}
62+
}

src/heap/ReorganizeString.java

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
package heap;
2+
3+
import java.util.HashMap;
4+
import java.util.Map;
5+
import java.util.PriorityQueue;
6+
import java.util.Queue;
7+
8+
/**
9+
* Description: https://leetcode.com/problems/reorganize-string
10+
* Difficulty: Medium
11+
* Time complexity: O(n)
12+
* Space complexity: O(1)
13+
*/
14+
public class ReorganizeString {
15+
16+
public String reorganizeString(String s) {
17+
Map<Character, Integer> frequencyMap = buildFrequencyMap(s);
18+
Queue<Map.Entry<Character, Integer>> maxHeap = new PriorityQueue<>(
19+
(e1, e2) -> Integer.compare(e2.getValue(), e1.getValue()));
20+
maxHeap.addAll(frequencyMap.entrySet());
21+
22+
StringBuilder possibleRearrangement = new StringBuilder();
23+
while (maxHeap.size() > 1) {
24+
Map.Entry<Character, Integer> first = maxHeap.poll();
25+
Map.Entry<Character, Integer> second = maxHeap.poll();
26+
27+
possibleRearrangement
28+
.append(first.getKey())
29+
.append(second.getKey());
30+
31+
int firstLeft = first.getValue();
32+
if (firstLeft > 1) {
33+
first.setValue(firstLeft - 1);
34+
maxHeap.offer(first);
35+
}
36+
37+
int secondLeft = second.getValue();
38+
if (secondLeft > 1) {
39+
second.setValue(secondLeft);
40+
maxHeap.offer(second);
41+
}
42+
}
43+
44+
if (!maxHeap.isEmpty()) {
45+
if (maxHeap.peek().getValue() > 1) {
46+
return "";
47+
} else {
48+
possibleRearrangement.append(maxHeap.poll().getKey());
49+
}
50+
}
51+
52+
return possibleRearrangement.toString();
53+
}
54+
55+
private Map<Character, Integer> buildFrequencyMap(String s) {
56+
Map<Character, Integer> frequencyMap = new HashMap<>();
57+
for (char c : s.toCharArray()) {
58+
frequencyMap.merge(c, 1, Integer::sum);
59+
}
60+
61+
return frequencyMap;
62+
}
63+
}

0 commit comments

Comments
 (0)