Array Element Repeater — Problem Statement & Solution Guide
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
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.
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
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;
}class Solution {
public:
int solution(vector<int>& nums, int k) {
int n = nums.size();
for (int i = 0; i < n - k + 1; i++) {
if (nums[i] == nums[i + k - 1] && isConsecutive(nums, i, k)) {
return i;
}
}
return -1;
}
private bool isConsecutive(vector<int>& nums, int start, int k) {
for (int i = 0; i < k; i++) {
if (nums[start + i] != nums[start]) {
return false;
}
}
return true;
}
};class Solution {
public int solution(int[] nums, int k) {
int n = nums.length;
for (int i = 0; i < n - k + 1; i++) {
if (nums[i] == nums[i + k - 1] && isConsecutive(nums, i, k)) {
return i;
}
}
return -1;
}
private boolean isConsecutive(int[] nums, int start, int k) {
for (int i = 0; i < k; i++) {
if (nums[start + i] != nums[start]) {
return false;
}
}
return true;
}
}def solution(nums, k):
n = len(nums)
for i in range(n - k + 1):
if nums[i] == nums[i + k - 1] and nums[i:i + k] == [nums[i]] * k:
return i
return -1function 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.