DSA AnimatorREVISION VIDEOS
← Back to problems
New

Happy Number — LeetCode 202 video explanation

Replace a number by the sum of the squares of its digits, again and again. It is happy if this reaches 1, otherwise it loops forever.

Loading videos…

DSA Animator › DSA Revision › Linked List › Happy Number

Key moments in the Happy Number video

0:03Problem0:11Example0:23Brute force0:29Key idea0:43Dry run0:53Code1:05Takeaway

What you will learn

Remember: any repeated next function forms a linked list. Floyd detects the loop without a set. The video solves Happy Number (LeetCode 202, Easy) with the Cycle Detection pattern from the Linked List topic, and you can replay every step in the interactive Happy Number animation.

Happy Number video transcript

Problem

Replace a number by the sum of the squares of its digits, again and again. It is happy if this reaches 1, otherwise it loops forever.

Example

19 goes to 82, then 68, then 100, then 1, so 19 is happy. 2 is not happy, because it falls into a loop through 4, 16, 37 and back to 4.

Brute force

You can store every number you see in a set and stop on a repeat. That uses extra memory.

Key idea

The sequence behaves like a linked list, where next is the digit square sum. So use fast and slow pointers, exactly as in cycle detection. If fast reaches 1, the number is happy, and if they meet elsewhere, it is not.

Dry run

Slow goes to 82 and fast to 68. Slow goes to 68, and fast jumps through 100 to 1. Fast has reached 1. So 19 is happy.

Code

In code, a helper computes the digit square sum. Move slow once and fast twice until fast is 1 or they meet. Return whether fast is 1, so it's O of log n per step and O of 1 space.

Takeaway

Remember: any repeated next function forms a linked list. Floyd detects the loop without a set.

More Linked List revision videos

← All 185 DSA revision videos