Social feed~15 min2s · 256 MBtarget O(n * c) time, O(n) spaceclassic twin: lc-202hashing
A feed team tags posts with a check number to test a new bucketing rule. Each post has a positive id. The check replaces the id by the sum of the squares of its digits, then does the same to the result, and so on.
An id is happy when this chain reaches 1. Otherwise the chain loops for ever without reaching 1. For example, the chain of the id 2 comes back to 4 after 9 steps, and 4 has been seen before.
The team has a list of up to 300,000 ids and wants to know how many of them are happy.
Write count_happy(ids).
ids[i] is the id of one post. It is a positive number.Input: ids = [19, 2, 7, 100]
Output: 3The id 19 gives the chain below, and it reaches 1.
| Step | Value | Next value |
|---|---|---|
| 0 | 19 | 82 |
| 1 | 82 | 68 |
| 2 | 68 | 100 |
| 3 | 100 | 1 |
| 4 | 1 | stop |
The id 7 and the id 100 also reach 1. The id 2 does not: its chain returns to 4 after 9 steps.
Input: ids = [1]
Output: 1The id 1 is already 1.
Input: ids = [4, 16, 37]
Output: 0These three ids are on the same loop, and none of them reaches 1.
1 ≤ ids.length ≤ 300,000 (posts)1 ≤ ids[i] ≤ 1,000,000,000 (post id)An id of at most 10^9 has at most 10 digits, so its first digit-square sum is at most 729. Every chain then lives among small numbers.
Every chain has a repeat or reaches 1 within a few steps. A set of the values met so far finds the repeat, and a shared table of verdicts lets later ids stop early.