Duplicate Adjacent

Concept Description

Sometimes, while traversing an array, you might want to compare each element with its immediate neighbor. One common reason for doing this is to find duplicate adjacent elements. You check if the next element in the array is the same as the current element, and if so, you can perform actions like printing them.

Java Example

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
public class Main {
    public static void main(String[] args) {
        int[] arr = {1, 2, 2, 3, 4, 4, 5};
        
        for(int i = 0; i < arr.length - 1; i++) {
            if(arr[i] == arr[i + 1]) {
                System.out.println("Duplicate adjacent elements: " + arr[i] + ", " + arr[i + 1]);
            }
        }
    }
}

C++ Example

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

int main() {
    int arr[] = {1, 2, 2, 3, 4, 4, 5};
    
    for(int i = 0; i < 6; i++) {
        if(arr[i] == arr[i + 1]) {
            cout << "Duplicate adjacent elements: " << arr[i] << ", " << arr[i + 1] << endl;
        }
    }
    return 0;
}

Python Example

1
2
3
4
5
arr = [1, 2, 2, 3, 4, 4, 5]

for i in range(len(arr) - 1):
    if arr[i] == arr[i + 1]:
        print(f"Duplicate adjacent elements: {arr[i]}, {arr[i + 1]}")

In these examples, we traverse the array and compare each element with its immediate next element. If they are the same, we print both elements. This is useful in scenarios where you want to identify adjacent duplicates in an array.