Skip to content

Commit 15a2c29

Browse files
committed
find largest subarray formed by consecutive integers from an integer array
1 parent db52497 commit 15a2c29

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,7 @@
8686
- [x] [Find sublists with zero sums](http://www.techiedelight.com/find-sub-array-with-0-sum/)
8787
- [x] [Sort binary list in linear time](https://www.techiedelight.com/sort-binary-array-linear-time/)
8888
- [x] [Find a duplicate element in a limited range array](http://www.techiedelight.com/find-duplicate-element-limited-range-array/)
89+
- [x] [Find largest sub-list formed by consecutive integers](http://www.techiedelight.com/find-largest-sub-array-formed-by-consecutive-integers/)
8990

9091
### Linked Lists
9192
<!-- Singly, doubly, circular linked list problems -->
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
// Given an integer array, find the largest subarray formed by consecutive integers. The subarray should contain all distinct values.
2+
package dataStructures.lists.longestSubarrayConsecutives;
3+
4+
import java.util.HashSet;
5+
import java.util.List;
6+
import java.util.Set;
7+
8+
public class LongestConsecutives {
9+
public static void main(String[] args) {
10+
List<Integer> input = List.of(2, 0, 2, 1, 4, 3, 1, 0);
11+
// Output: The largest subarray is { 0, 2, 1, 4, 3 }
12+
13+
int n = input.size();
14+
int maxLen = 0;
15+
int startIndex = 0;
16+
17+
for (int i = 0; i < n; i++) {
18+
int minVal = input.get(i);
19+
int maxVal = input.get(i);
20+
21+
Set<Integer> encountered = new HashSet<>();
22+
23+
for (int j = i; j < n; j++) {
24+
var value = input.get(j);
25+
if (encountered.contains(value)) {
26+
break;
27+
} else {
28+
encountered.add(value);
29+
minVal = Math.min(minVal, value);
30+
maxVal = Math.max(maxVal, value);
31+
}
32+
if (maxVal - minVal == j - i) {
33+
int len = j - i + 1;
34+
if (len > maxLen) {
35+
maxLen = len;
36+
startIndex = i;
37+
}
38+
}
39+
}
40+
}
41+
System.out.println("Largest subarray: " + input.subList(startIndex, startIndex + maxLen));
42+
}
43+
}

0 commit comments

Comments
 (0)