VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-of-elements-that-are-kth-powers-of-their-indices-in-given-array/

⇱ Count of elements that are Kth powers of their indices in given Array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count of elements that are Kth powers of their indices in given Array

Last Updated : 23 Jul, 2025

Given an array arr[] with N non-negative integers, the task is to find the number of elements that are Kth powers of their indices, where K is a non-negative number.

arr[i] = iK 

Example:

Input: arr = [1, 1, 4, 3, 16, 125, 1], K = 0
Output: 3
Explanation: 3 elements are Kth powers of their indices:
00 is 1, 10 is 1, and 60 is 1

Input: arr = [0, 1, 4, 3], K = 2
Output: 2
Explanation: 02 is 0, 12 is 1, and 22 is 4

Approach: Given problem can be solved by finding the Kth powers of every index and checking if they are equal to the element present at that index. Follow the steps below to solve the problem:

  • Initialize a variable res to 0 for storing the answer
  • If the value of K is 0:
    • If the first element in the array arr exists and is equal to 1 then increment res by 1
  • Else if the value of K is greater than 0:
    • If the first element in the array arr exists and is equal to 0 then increment res by 1
  • If the second element in the array arr exists and is equal to 1 then increment res by 1
  • Iterate the array arr from index 2 till the end and at every index:
    • Initialize a variable indPow to the current index i and multiply it by i, k-1 times
    • If the value of indPow becomes equal to the current element arr[i] then increment res by 1
  • Return res as our answer

Below is the implementation of the above approach:
 


Output
3

Time Complexity: O(N * K)
Auxiliary Space: O(1)

Comment
Article Tags: