How I Won an Algorithm Competition at University — With a Smart Trick | Mahdi Shamlou

Published: (February 19, 2026 at 07:21 AM EST)
2 min read
Source: Dev.to

Source: Dev.to

Introduction

Today I want to share something different from my usual LeetCode posts.
I recently participated in an algorithm and programming competition at Islamic Azad University and won! 🎉

Problem Statement

We had to design two cubes with digits on their faces so that we could display every number from 0 to n by placing the cubes side‑by‑side.

Rules

  • Each cube has 6 faces (6 digits).
  • By placing the cubes side‑by‑side, we must form all numbers from 0 → n.
  • If possible, output the cube configuration; otherwise return "Impossible".

Important detail: We cannot rotate 6 to become 9.

Observation

At first glance the problem looks like a brute‑force search:

  1. Generate combinations of digits for each cube.
  2. Test all permutations.
  3. Check whether every number up to n can be displayed.

However, the number of valid configurations is extremely limited. By reasoning about the required digits we can determine the maximum achievable upper bound.

Because we need digit 9 explicitly and cannot reuse 6 as 9, the largest n that can be represented is 30. For any n > 30 the answer is "Impossible".

Solution

The valid configuration can be pre‑computed manually:

  • Cube 1: [1, 2, 3, 4, 5, 6]
  • Cube 2: [0, 1, 2, 7, 8, 9]

With this arrangement we can display every number from 0 to 30.

Code (Python)

def two_cubes_solution(n):
    """Return the digit configuration for two cubes that can display
    all numbers from 0 to n, or 'Impossible' if n > 30."""
    # Impossible case
    if n > 30:
        return "Impossible"

    # Pre‑calculated cube faces (solved manually)
    cube1 = [1, 2, 3, 4, 5, 6]
    cube2 = [0, 1, 2, 7, 8, 9]

    return cube1, cube2


# Example usage
if __name__ == "__main__":
    n = int(input())
    print(two_cubes_solution(n))

Complexity: O(1) time and O(1) space.

Takeaway

Sometimes the smartest algorithm is to solve the logic once (e.g., by hand) and let the code remain simple. I’ll share the next competition problem soon—it was much more algorithm‑heavy.

0 views
Back to Blog

Related posts

Read more »

Leetcode 696 Solution Explained

!pichttps://media2.dev.to/dynamic/image/width=256,height=,fit=scale-down,gravity=auto,format=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farti...

Apex B. OpenClaw, Local Embeddings.

Local Embeddings para Private Memory Search Por default, el memory search de OpenClaw envía texto a un embedding API externo típicamente Anthropic u OpenAI par...