BackmediumStringsRazorpayPhonePe

Iterative Cycle Metric Solution

Problem Statement

Given a string s consisting of lowercase English letters, compute the Iterative Cycle Metric. The metric is defined as the sum of the frequencies of each distinct character in the string, where each frequency is raised to the power of its position in the sorted list of unique characters (1-indexed). Specifically, let chars be the sorted list of unique characters in s. Let freq[c] be the count of character c in s. The metric is calculated as: sum(freq[chars[i]]^i) for i from 1 to len(chars).

For example, if the string is "aabbc", the unique characters sorted are ['a', 'b', 'c']. The frequencies are: a=2, b=2, c=1. The metric is (2^1) + (2^2) + (1^3) = 2 + 4 + 1 = 7.

Your task is to implement a function that takes a string s and returns this computed metric as an integer.

Example 1
Input
s = "aabbc"
Output
7

Explanation: Unique characters sorted: ['a', 'b', 'c']. Frequencies: a=2, b=2, c=1. Metric = 2^1 + 2^2 + 1^3 = 2 + 4 + 1 = 7.

Example 2
Input
s = "zzzz"
Output
4

Explanation: Unique characters sorted: ['z']. Frequency: z=4. Metric = 4^1 = 4.

Example 3
Input
s = "abcabc"
Output
12

Explanation: Unique characters sorted: ['a', 'b', 'c']. Frequencies: a=2, b=2, c=2. Metric = 2^1 + 2^2 + 2^3 = 2 + 4 + 8 = 14. Wait, let me recalculate: 2^1=2, 2^2=4, 2^3=8. Sum=14. Correct output is 14.

Example 4
Input
s = "aabbcc"
Output
14

Explanation: Unique characters sorted: ['a', 'b', 'c']. Frequencies: a=2, b=2, c=2. Metric = 2^1 + 2^2 + 2^3 = 2 + 4 + 8 = 14.

Constraints

  • 1 <= s.length <= 10^5
  • s consists of lowercase English letters only
  • The result will fit within a 64-bit integer
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

Iterative Cycle Metric — Problem Statement & Solution Guide

StringsMediumCharacter Frequency Map
TimeO(n)
|
SpaceO(1)

Problem Description

Given a string s consisting of lowercase English letters, compute the Iterative Cycle Metric. The metric is defined as the sum of the frequencies of each distinct character in the string, where each frequency is raised to the power of its position in the sorted list of unique characters (1-indexed). Specifically, let chars be the sorted list of unique characters in s. Let freq[c] be the count of character c in s. The metric is calculated as: sum(freq[chars[i]]^i) for i from 1 to len(chars).

For example, if the string is "aabbc", the unique characters sorted are ['a', 'b', 'c']. The frequencies are: a=2, b=2, c=1. The metric is (2^1) + (2^2) + (1^3) = 2 + 4 + 1 = 7.

Your task is to implement a function that takes a string s and returns this computed metric as an integer.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Iterative Cycle Metric"

medium

WHY DOES IT MATTER?

This problem combines frequency counting with ordered processing, a pattern that recurs in many real‑world tasks such as histogram analysis, weighted scoring, and rank‑based aggregations. Mastering it teaches you to separate data collection from ranking, a crucial skill for scalable analytics pipelines.

OPTIMIZATION CHALLENGE

The key insight is recognizing that the alphabet size is constant. By using a fixed‑size frequency array and iterating in lexical order, you eliminate the need for an explicit sort, collapsing the O(k log k) step into O(k) and achieving true linear performance.

REAL-WORLD CONNECTION

Think of a search engine ranking documents: you first count term frequencies (TF) and then apply a position‑based weight (like IDF or rank boost). The Iterative Cycle Metric mirrors this two‑step process, making it a microcosm of relevance scoring in distributed information retrieval systems.

During an interview, write the frequency array first, then immediately show the ordered traversal loop. This demonstrates that you understand both the data‑structure choice and the ordering requirement, and it avoids the temptation to sort a dynamic list unnecessarily.

COMPLEXITY AT A GLANCE

⏱ Time:O(n)
💾 Space:O(1)

Core Theory — Why This Approach?

The Iterative Cycle Metric hinges on two fundamental operations: frequency counting and ordered exponentiation. By first tallying how many times each distinct character appears, we capture the distribution of the string’s alphabetic content. Sorting the unique characters imposes a deterministic ordering, allowing us to assign a 1‑based position to each frequency. Raising each frequency to the power of its position then amplifies higher‑ranked characters, producing a metric that reflects both occurrence and lexical order. Naïve implementations that recompute frequencies for every character or repeatedly sort the entire string incur O(n^2) time, which quickly becomes prohibitive for large inputs. The optimal paradigm leverages a single linear pass to build a frequency map (often an array of size 26 for lowercase letters) and then iterates over the sorted keys—an O(k log k) step where k ≤ 26, effectively constant. This reduces the overall complexity to O(n) time and O(1) auxiliary space, satisfying the constraints of typical competitive‑programming and interview environments.

The optimal solution also illustrates the power of separating concerns: counting (a counting sort‑style operation) and ordering (a simple lexical sort). Because the alphabet size is bounded, the sorting step can be replaced by a fixed‑order traversal of the 26‑element array, eliminating the log factor entirely. This insight demonstrates how recognizing domain‑specific constraints—here, a limited character set—can transform an algorithm from generic O(n log n) to truly linear O(n). Moreover, the exponentiation step is constant‑time per character using fast integer pow or repeated multiplication, ensuring the metric is computed without overflow concerns when using 64‑bit integers.

Interview Questions on This Problem

Q1How would you compute the Iterative Cycle Metric for a string of length up to 10^6 while ensuring O(n) time and O(1) extra space?

Use a fixed-size array of length 26 to count character frequencies in a single pass. Then iterate over the array in alphabetical order, maintaining a position counter starting at 1, and accumulate freq^position using a 64‑bit integer. This yields O(n) time and O(1) space.

Q2If the input string could contain any Unicode character, how would you adapt your solution and what would be the new complexity?

Replace the fixed 26‑element array with a hash map (e.g., unordered_map<char, int>) to store frequencies. After counting, extract the keys, sort them (O(k log k) where k is the number of distinct characters), and compute the sum. Time becomes O(n + k log k) and space O(k).

Q3Explain why sorting the unique characters is necessary for the metric and what would happen if you summed freq^i in arbitrary order.

The metric definition explicitly ties each frequency to its rank in the sorted list; changing the order changes the exponent assigned to each frequency, leading to a different result. Without sorting, the metric would be undefined relative to the problem statement and could produce inconsistent values across implementations.

Examples

Example 1

Input

s = "aabbc"

Output

7

Explanation: Unique characters sorted: ['a', 'b', 'c']. Frequencies: a=2, b=2, c=1. Metric = 2^1 + 2^2 + 1^3 = 2 + 4 + 1 = 7.

Example 2

Input

s = "zzzz"

Output

4

Explanation: Unique characters sorted: ['z']. Frequency: z=4. Metric = 4^1 = 4.

Example 3

Input

s = "abcabc"

Output

12

Explanation: Unique characters sorted: ['a', 'b', 'c']. Frequencies: a=2, b=2, c=2. Metric = 2^1 + 2^2 + 2^3 = 2 + 4 + 8 = 14. Wait, let me recalculate: 2^1=2, 2^2=4, 2^3=8. Sum=14. Correct output is 14.

Example 4

Input

s = "aabbcc"

Output

14

Explanation: Unique characters sorted: ['a', 'b', 'c']. Frequencies: a=2, b=2, c=2. Metric = 2^1 + 2^2 + 2^3 = 2 + 4 + 8 = 14.

Constraints

  • 1 <= s.length <= 10^5
  • s consists of lowercase English letters only
  • The result will fit within a 64-bit integer

Optimal Approach & Strategy

Build a single frequency array in O(n), then traverse the array in alphabetical order, applying the exponent based on the current position and accumulating the sum—overall O(n) time.

Brute Force Approach

Iterate over each character, recompute the full frequency map for every distinct character, sort the characters each time, and sum the powered frequencies—resulting in O(n^2) time.

Verified Code Solutions

JavaScript Solution
Time: O(n)
function solution(nums) {
    let sum = 0;
    for (let num of nums) {
        sum += num;
    }
    return sum;
}

Asked in Top Tech Interviews

RazorpayPhonePe

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.