forked from Ayu-99/Data-Structures
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFind Duplicate Number.java
More file actions
33 lines (26 loc) · 848 Bytes
/
Find Duplicate Number.java
File metadata and controls
33 lines (26 loc) · 848 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
//brute-force approach
import java.util.HashMap;
class Solution {
public static int findDuplicate(int[] nums) {
HashMap<Integer, Integer> map = new HashMap<>();
for (int num : nums) {
if (map.containsKey(num)) {
return num; // duplicate found
}
map.put(num, 1);
}
return -1; // ideally shouldn't happen if duplicate is guaranteed
}
}
//optimized approach:
class Solution {
public static boolean containsDuplicate(int[] nums) {
for (int i = 0; i < nums.length; i++) {
int idx = Math.abs(nums[i]);
if (nums[idx] < 0) return true;
nums[idx] = -nums[idx];
}
return false;
}
}
//check out my youtube channel where I solve DSA problems: https://www.youtube.com/@AyushiSharmaDSA/videos