Non-Cyclical Numbers

Exploring Non-Cyclical Numbers: A Step-by-Step Guide

In mathematics and computer science, certain problems help us uncover patterns within numbers. One such intriguing concept is non-cyclical numbers, also known as “happy numbers.”

In this article, we’ll explore what makes a number non-cyclical, understand its algorithm, and implement an efficient solution.

Happy numbers neetcode

What is a Non-Cyclical Number?

A non-cyclical number is defined by an iterative process where you repeatedly replace a number with the sum of the squares of its digits. The process ends in one of two ways:

  1. The number eventually equals 1 (making it a non-cyclical number).
  2. The number falls into a repetitive cycle that does not include 1.

If the process stops at 1, the number is classified as non-cyclical. Otherwise, it is cyclical.

Problem Statement

Given a positive integer n, determine whether it is a non-cyclical number.

Constraints:

  • 1 <= n <= 1000

Explanation: 1^2 + 0^2 + 0^2 = 1

Explanation:
Explanation:
1^2 + 0^2 + 1^2 = 2
2^2 = 4
4^2 = 16
1^2 + 6^2 = 37
3^2 + 7^2 = 58
5^2 + 8^2 = 89
8^2 + 9^2 = 145
1^2 + 4^2 + 5^2 = 42
4^2 + 2^2 = 20
2^2 + 0^2 = 4 (This number has already been seen)

Approach to Solve the Problem

To determine whether a number is non-cyclical, we must repeatedly calculate the sum of the squares of its digits. During this process, we need to:

  1. Stop if we reach the number 1.
  2. Detect cycles by keeping track of previously encountered numbers.

Algorithm

  1. Define a helper function sum_of_squares that calculates the sum of the squares of the digits of a number.
  2. Use a set to store numbers that have already been seen.
  3. Loop until:
    • The number equals 1 (return true).
    • A previously seen number is encountered (return false).

There are mainly three approach to solve this problem – 

  1. Hash Set
  2. Fast And Slow Pointers – I
  3. Fast And Slow Pointers – II

1. Hash Set 

  • Time complexity: O(logn)
  • Space complexity: O(logn)

2. Fast And Slow Pointers – I

Time & Space Complexity
  • Time complexity: O(logn)
  • Space complexity: O(1)

Code

3. Fast And Slow Pointers – II

  • Time complexity: O(logn)
  • Space complexity: O(1)

Code

More Articles