Javatpoint Logo
Javatpoint Logo

Write Python Program to First Repeating Element from the List

In this tutorial, we will write the program to find the index of first repeating element from the list. It is an easy problem which can be asked in the interview. Let's see the following problem statement.

Problem Statement

We are given an array of integers array with length n. Find the first element that appears more than once in the array, and return its index, which should be the smallest among all repeating elements. If there are no repeating elements in the array, return -1.

Solution

To solve this problem, we will use the hash table to store the table frequency of each element as we traverse the element. Let's understand the following code snippet.

Example -

Output:

2

Explanation -

In this code, we first initialize an empty dictionary freq to store the frequency of each element. We then traverse the array arr and update the frequency of each element in freq. After that, we traverse arr again and return the index and value of the first element with a frequency greater than 1. If there is no such element, we return -1.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA