BackeasyArrays

Array Element Repeater Solution

Problem Statement

You are given an array of integers and an integer k, find the first element that repeats k times consecutively in the array and return its index, if no such element exists return -1.

Example 1
Input
[1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5]
Output
3

Explanation: Step-by-step: with input [1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5], we check each element from index 0 to 19. At index 3, the element 2 repeats 4 times consecutively, which is the first occurrence. Therefore, the output is 3.

Example 2
Input
[1, 2, 3, 4, 5]
Output
-1

Explanation: Step-by-step: with input [1, 2, 3, 4, 5], we check each element from index 0 to 4. Since no element repeats k times consecutively, the output is -1.

Constraints

  • 1 <= k <= 100
  • 1 <= array length <= 1000
  • 1 <= element value <= 1000
Live Compiler1 Free Run Available
Loading Editor...
Test Cases & Output
Click "Run" to test your 1 free compile trial!

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free

Array Element Repeater — Problem Statement & Solution Guide

ArraysEasy1 task / each of 2 patterns: Easy + Medium
TimeO(n)
|
SpaceO(1)

Problem Description

You are given an array of integers and an integer k, find the first element that repeats k times consecutively in the array and return its index, if no such element exists return -1.

Examples

Example 1

Input

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

Output

3

Explanation: Step-by-step: with input [1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5], we check each element from index 0 to 19. At index 3, the element 2 repeats 4 times consecutively, which is the first occurrence. Therefore, the output is 3.

Example 2

Input

[1, 2, 3, 4, 5]

Output

-1

Explanation: Step-by-step: with input [1, 2, 3, 4, 5], we check each element from index 0 to 4. Since no element repeats k times consecutively, the output is -1.

Constraints

  • 1 <= k <= 100
  • 1 <= array length <= 1000
  • 1 <= element value <= 1000

Optimal Approach & Strategy

Master coding challenges related to Arrays and solve the Array Element Repeater problem optimally.

Verified Code Solutions

JavaScript Solution
Time: O(n)
function solution(nums, k) {
   let n = nums.length;
   for (let i = 0; i < n - k + 1; i++) {
       if (nums[i] === nums[i + k - 1] && nums.slice(i, i + k).every((val, idx) => val === nums[i + idx])) {
           return i;
       }
   }
   return -1;
}

Solve in Interative Editor

Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.