878900. Find Only Repetitive Element from 1 to n-1

Easy

Here is the Markdown blog post for the problem:

Find Only Repetitive Element from 1 to n-1

Slug: find-repetitive-element-from-1-to-n-1 Difficulty: Easy Id: 878900 Topic Tags: two-pointer-algorithm, Arrays Company Tags: None

Summary

This problem is about finding the only repetitive element in an array of numbers from 1 to n-1. The key concept involved is the two-pointer algorithm.

Detailed Explanation

The given array contains elements from 1 to n-1. To solve this problem, we use the two-pointer algorithm. We initialize two pointers, one at the start and one at the end of the array. Then, we compare the values at these positions. If they are equal, it means that the element is repetitive and we return it.

Here's a step-by-step breakdown of the solution:

  1. Initialize two pointers, start and end, to the start and end of the array respectively.
  2. Compare the values at the positions pointed by start and end.
  3. If they are equal, return that element as it is repetitive.
  4. Move the pointer with the smaller value towards the other pointer until they point to the same element again.
  5. That element is the only repetitive element in the array.

The time complexity of this algorithm is O(n) where n is the number of elements in the array, and the space complexity is O(1).

Optimized Solutions

Java

View on GeeksforGeeks
public class Solution {
    public int findRepetitiveElement(int[] arr) {
        if (arr.length == 0) return -1;
        int start = 0, end = arr.length - 1;
        while (start < end) {
            int mid = start + (end - start) / 2;
            if (arr[mid] != arr[start]) {
                start = mid + 1;
            } else {
                end = mid;
            }
        }
        return arr[start];
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.