Mark Duplicate Elements by Replacing Them with -1

In an array, you may sometimes want to identify duplicate elements and mark them for further action. One simple way to do this is to replace duplicates with a special value, such as -1. This operation is useful in scenarios where you need to maintain the array’s structure but want to invalidate duplicates. When the array is sorted, the task is even simpler, as adjacent elements can be easily compared.

Example Code

Java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
public class Main {
  public static void main(String[] args) {
    int[] array = {1, 2, 2, 3, 4, 4, 5};
    
    for (int i = 0; i < array.length - 1; i++) {
      if (array[i] == array[i + 1]) {
        array[i + 1] = -1;
      }
    }
    
    for (int num : array) {
      System.out.print(num + " ");
    }
  }
}
C++
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
using namespace std;

int main() {
  int array[] = {1, 2, 2, 3, 4, 4, 5};
  int length = sizeof(array) / sizeof(array[0]);
  
  for (int i = 0; i < length - 1; i++) {
    if (array[i] == array[i + 1]) {
      array[i + 1] = -1;
    }
  }
  
  for (int i = 0; i < length; i++) {
    cout << array[i] << " ";
  }
  
  return 0;
}
Python
1
2
3
4
5
6
7
array = [1, 2, 2, 3, 4, 4, 5]

for i in range(len(array) - 1):
    if array[i] == array[i + 1]:
        array[i + 1] = -1

print(array)

Key Takeaways

  • Duplicates are identified by comparing adjacent elements in the sorted array.
  • When a duplicate is found, the element is marked by replacing it with -1.
  • The array structure remains the same; only the value of the duplicate element changes.