Apple OA Interview Question: Grouping Sums

17 Views
No Comments

Grouping Sums

Given a string s made of digits (0-9), treat consecutive equal digits as a group. For each group, add it to a running total. Return the total.

Example:

s = "11120333"
Groups: 111, 2, 0, 333
Return: 1 * 3 + 2 * 1 + 0 * 1 + 3 * 3 = 14

The task is to scan the digit string once, split it into consecutive equal-digit groups, and sum each group's digit value multiplied by its length. For example, "11120333" becomes 111, 2, 0, 333, producing 1×3 + 2×1 + 0×1 + 3×3 = 14. A simple linear pass with a running count is enough, making the solution O(n) time and O(1) extra space.

END
 0