Keep Track of Last Duplicate in a Variable

Concept Description

In problems dealing with arrays, sometimes it’s important to keep track of duplicate elements for tasks like removal or replacement. One way to manage duplicates is by keeping track of the last duplicate element in a variable. As we traverse the array, we update this variable whenever we find a new duplicate. This way, we can make decisions based on the last duplicate encountered during any point in our traversal.

Java Example

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
public class Main {
    public static void main(String[] args) {
        int[] arr = {1, 2, 2, 3, 4, 4, 5};
        int lastDuplicate = Integer.MIN_VALUE;

        for(int i = 1; i < arr.length; i++) {
            if(arr[i] == arr[i-1]) {
                lastDuplicate = arr[i];
            }
        }

        System.out.println("Last duplicate is: " + lastDuplicate);
    }
}

C++ Example

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
#include <iostream>
using namespace std;

int main() {
    int arr[] = {1, 2, 2, 3, 4, 4, 5};
    int lastDuplicate = INT_MIN;

    for(int i = 1; i < 7; i++) {
        if(arr[i] == arr[i-1]) {
            lastDuplicate = arr[i];
        }
    }

    cout << "Last duplicate is: " << lastDuplicate << endl;
    return 0;
}

Python Example

1
2
3
4
5
6
7
8
arr = [1, 2, 2, 3, 4, 4, 5]
last_duplicate = float('-inf')

for i in range(1, len(arr)):
    if arr[i] == arr[i-1]:
        last_duplicate = arr[i]

print(f"Last duplicate is: {last_duplicate}")

In these examples, a variable lastDuplicate is maintained to keep track of the last duplicate element encountered while traversing the array. After the loop, we can use this variable as needed for our problem’s requirements.