Home > Back-end >  Track first index at which a duplicate value is observed when using local variable
Track first index at which a duplicate value is observed when using local variable

Time:09-15

Given int[] arr = [7, 2, 5, 2]; and int index;, how can I use a for loop to make sure that index is assigned to 1 (the first index at which 2 was observed in arr) and not 3 (the last index at which 2 was observed in arr)?

I'm thinking using a break; statement but I'm not sure how to implement the syntax.

CodePudding user response:

You can add every array value to a hashmap with the value as key and the index as value, that way if a key already exists you know at which index it was.

Alternatively you could also have the hashmap value be a list so you can store for each value, all of the indexes in which is appears in the array.

If you're using embedded for loops (the suggested answer when you search this question) one of your loop counters will point to the first instance while the second will point to the second instance. Just use the correct variable.

You can break a for loop once you've found what you want, like this:

for (int i = 0; i < arr.length; i  ) {
    if (foundDuplicate()) {
        break;
    }
}
// You end up here after the break

This gets you out of the for loop

You can also find the duplicate whichever way you want and then iterate over the array until you find the first instance.

Depends on what arbitrary rules have been placed on this exercise

  • Related