Skip to content
Closed
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
46 changes: 46 additions & 0 deletions Misc/largestRange.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import java.util.*;

public class largestRange {

// Finds the length of longest occurring consecutive numbers range in an array
public static int longestRange(int[] nums) {
int longestRange = 0;
HashMap<Integer, Boolean> num = new HashMap<>();

/**
* Stores a mapping of a number to whether the current number is part of a particular
* consecutive range or not.
*/
for (int x : nums) num.put(x, true);
Copy link

@prashantdoshi28 prashantdoshi28 Nov 12, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure but can't we just use lookahead type of approach over here?

For example,

int[] input_arr = new int[]{0,1,2,4,5,6,0,1};
int count = 1;
int temp_count = 1;
for (int i = 1; i < input_arr.length; i++) {
    if (input_arr[i] != input_arr[i - 1] + 1) {
        if (temp_count > count) {
            count = temp_count;
        }
        temp_count = 1;
    } else temp_count++;
}
System.out.println(count); // Prints 3

If I have misunderstood requirements or this does not work as intended (I haven't tested it, so it is be possible), please let me know.

If above works just as fine, please can you explain this approach's necessity?

This is just a suggestion, not a requirement.

Please do needful and let me know.

for (int x : nums) {
if (!num.get(x)) continue;
num.replace(x, false);
int currentRange = 1;
int left = x - 1;
int right = x + 1;
while (num.containsKey(left)) { // Search leftwards for consecutive range
num.replace(left, false);
currentRange += 1;
left--;
}
while (num.containsKey(right)) { // Search rightwards for consecutive range
num.replace(right, false);
currentRange += 1;
right++;
}
if (currentRange > longestRange)
longestRange = currentRange; // Store longest range at every interation
}
return longestRange;
}

public static void main(String[] args) {
// Testcases
assert longestRange(new int[] {1, 2, 3, 4, -1, 11, 10}) == 4;
// The longest consecutive number range is of length 4 i.e. {1, 2, 3, 4}
assert longestRange(new int[] {-1, 1, 3, 5, 7}) == 1;
// The longest consecutive number range is of length 1 i.e. any of the elements alone
assert longestRange(new int[] {0, 1, 2, 3, 4, 7, 6, 5}) == 8;
// The longest consecutive number range is of length 8 i.e. {0, 1, 2, 3, 4, 5, 6, 7}
}
}