Google Interview Question: Happy Numbers

How to solve the Happy numbers problem using Python

Image for post
Image for post
Photo by Nick Hillier on Unsplash

The question:

Write an algorithm to determine if a number n is happy.

A happy number is a number defined by the following process:

Starting with any positive integer, replace the number by the sum of the squares of its digits.

Repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1.

Those numbers for which this process ends in 1 are happy.

Return true if n is a happy number, and false if not.

We are given an example of how the output should look like:

Input: n = 19
Output: true
Explanation:
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1

Example 2:

Input: n = 2
Output: false

This is a common interview problem especially with the company Google. As someone preparing for software engineering interview problems you would definitely want to know how to approach and solve this problem. In this article we are going to have a look at the steps for solving this.

I advice that you first try and solve it on your own first before having a look at the solution!

The solution:

As seen in the example above we want our code to be able to square and sum the digits as well as determine whether the final result is one or whether the result ends up in an endless loop cycle.

To do this we will make use of while loops as well as sets.

Below is the code that shows the algorithm

happy numbers solution

The solution above makes good use of space and time! Feel free to comment below on other approaches of solving this problem.

Written by

Software engineer. I write about my journey, Machine Learning, Web application development and also Python!

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store