BackmediumStringsPhonePeSalesforce

Iterative Path Weight Solution

Problem Statement

Given a non‑empty string S consisting only of lowercase English letters, define a transformation T as follows: for every character c in the current string, compute f(c), the number of occurrences of c in that string, and replace c by the decimal representation of f(c). Concatenating these replacements from left to right yields the next string. Starting with S0 = S, repeatedly apply the transformation (Si+1 = T(Si)) until the string no longer changes (Si+1 == Si). The iterative path weight is defined as the sum of the lengths of all strings generated during this process, including the initial string and the final stable string. Output this weight.

Formally, let |X| denote the length of string X. Compute weight = |S0| + |S1| + … + |Sk| where Sk is the first string for which T(Sk) = Sk. Return weight as a 64‑bit integer.

Example 1
Input
abac
Output
16

Explanation: S0 = "abac" (length 4). Frequencies: a=2, b=1, c=1 → S1 = "2121" (length 4). In S1, '2' appears 2 times and '1' appears 2 times → S2 = "2222" (length 4). In S2, '2' appears 4 times → S3 = "4444" (length 4). Applying T to "4444" yields the same string, so the process stops. Weight = 4+4+4+4 = 16.

Example 2
Input
aaaa
Output
8

Explanation: S0 = "aaaa" (length 4). All characters are 'a' with frequency 4 → S1 = "4444" (length 4). In "4444" each character appears 4 times, so T("4444") = "4444" and the process stops. Weight = 4+4 = 8.

Example 3
Input
abc
Output
9

Explanation: S0 = "abc" (length 3). Each character occurs once → S1 = "111" (length 3). In "111" the digit '1' occurs 3 times → S2 = "333" (length 3). T("333") = "333", so the iteration ends. Weight = 3+3+3 = 9.

Constraints

  • 1 <= |S| <= 100000
  • S contains only characters 'a' through 'z'
  • The answer fits in a signed 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 Path Weight — Problem Statement & Solution Guide

StringsMediumCharacter Frequency Map
TimeO(n)
|
SpaceO(1) additional (frequency array of size 26 or 10)

Problem Description

Given a non‑empty string S consisting only of lowercase English letters, define a transformation T as follows: for every character c in the current string, compute f(c), the number of occurrences of c in that string, and replace c by the decimal representation of f(c). Concatenating these replacements from left to right yields the next string. Starting with S0 = S, repeatedly apply the transformation (Si+1 = T(Si)) until the string no longer changes (Si+1 == Si). The iterative path weight is defined as the sum of the lengths of all strings generated during this process, including the initial string and the final stable string. Output this weight.

Formally, let |X| denote the length of string X. Compute

weight = |S0| + |S1| + … + |Sk|

where Sk is the first string for which T(Sk) = Sk. Return weight as a 64‑bit integer.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Iterative Path Weight"

medium

WHY DOES IT MATTER?

Frequency‑based encoding appears in data compression, histogram generation, and self‑describing sequences. Mastering the technique teaches you how to replace costly per‑element scans with global aggregates, a core skill for scaling string‑heavy workloads.

OPTIMIZATION CHALLENGE

The breakthrough is to decouple counting from replacement: compute a global frequency map in one linear pass, then build the next string in another pass. This eliminates the quadratic blow‑up of the naïve double‑loop and leverages the fact that after the first iteration the alphabet size drops to ten.

REAL-WORLD CONNECTION

Think of a distributed log aggregation system: each node reports how many times it saw a particular event type. The central collector replaces each event label with its count, similar to T, and then repeats the aggregation to produce a concise summary of the entire system.

During an interview, first state the O(n²) naïve idea, then immediately propose the O(n) frequency map, and finally argue about convergence to a fixed point to bound the total work. This shows both algorithmic insight and practical awareness of input characteristics.

COMPLEXITY AT A GLANCE

⏱ Time:O(n)
💾 Space:O(1) additional (frequency array of size 26 or 10)

Core Theory — Why This Approach?

The transformation T is a frequency‑encoding operation. In each iteration we replace every character by the count of how many times that character appears in the current string. Naïvely implementing T by scanning the whole string for each character leads to O(n²) time because for every position we would recompute its frequency. The optimal paradigm is to perform a single pass to build a frequency map (O(n)) and then construct the next string in a second linear pass, yielding O(n) per iteration. Moreover, after the first iteration the alphabet collapses from 26 letters to at most 10 digit symbols, and the process quickly reaches a fixed point (a self‑descriptive numeric string). Recognising this convergence allows us to bound the number of iterations to a small constant (typically ≤ 5), turning the overall algorithm into O(n) time overall.

Interview Questions on This Problem

Q1How would you compute the string after k applications of the transformation T for a given input S, where k can be up to 10⁹?

First simulate T until the string stops changing; this happens in ≤ 5 iterations because the alphabet reduces to digits and the process reaches a fixed point. Record the iteration at which convergence occurs. If k exceeds that iteration count, the answer is the fixed point string; otherwise return the string at iteration k.

Q2Why does the length of the string never increase beyond the original length after the first transformation?

Each character is replaced by the decimal representation of its frequency, which is at most the length of the string. Since the sum of all frequencies equals the original length, the total number of digits produced cannot exceed the original length; in practice it often shrinks because many frequencies are single‑digit.

Q3Can you prove that the transformation T always reaches a stable string in O(1) iterations regardless of the input size?

After the first iteration all symbols are digits 0‑9. The next iteration counts digit frequencies, producing a new numeric string whose length is bounded by the number of distinct digits (≤ 10) times the maximum digit count (≤ 9), i.e., ≤ 20 characters. Re‑applying T on such a short string can only produce a string of length ≤ 20 again, and the state space of possible strings of that size is tiny, guaranteeing convergence within a constant number of steps.

Examples

Example 1

Input

abac

Output

16

Explanation: S0 = "abac" (length 4). Frequencies: a=2, b=1, c=1 → S1 = "2121" (length 4). In S1, '2' appears 2 times and '1' appears 2 times → S2 = "2222" (length 4). In S2, '2' appears 4 times → S3 = "4444" (length 4). Applying T to "4444" yields the same string, so the process stops. Weight = 4+4+4+4 = 16.

Example 2

Input

aaaa

Output

8

Explanation: S0 = "aaaa" (length 4). All characters are 'a' with frequency 4 → S1 = "4444" (length 4). In "4444" each character appears 4 times, so T("4444") = "4444" and the process stops. Weight = 4+4 = 8.

Example 3

Input

abc

Output

9

Explanation: S0 = "abc" (length 3). Each character occurs once → S1 = "111" (length 3). In "111" the digit '1' occurs 3 times → S2 = "333" (length 3). T("333") = "333", so the iteration ends. Weight = 3+3+3 = 9.

Constraints

  • 1 <= |S| <= 100000
  • S contains only characters 'a' through 'z'
  • The answer fits in a signed 64‑bit integer

Optimal Approach & Strategy

Build a frequency map in O(n) time, then construct the next string in another O(n) pass; repeat until the string no longer changes (≤ 5 iterations).

Brute Force Approach

For each character, scan the whole string to count its occurrences and replace it, leading to O(n²) time per iteration.

Verified Code Solutions

JavaScript Solution
Time: O(n)
function iterativePathWeight(nums) {
      let sum = 0;
      for (let i = 0; i < nums.length; i++) {
         sum += nums[i];
      }
      return sum;
   }

Asked in Top Tech Interviews

PhonePeSalesforce

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.