The Utopian Tree Algorithm

"Someone say Groot..."?

Β·

5 min read

Howdy fellow programmers! πŸ‘‹πŸ½

In this article, I'll be describing how I solved the Utopian Tree Challenge on HackerRank using Python 3.

This challenge is part of the Implementation challenges in the Algorithm section on HackerRank.

If this is your first time reading my data structures and algorithms article, please consider reading more in my Algos in Plain English series.πŸ˜ƒ

Problem 🎲

The Utopian Tree goes through 2 cycles of growth every year. Each spring, it doubles in height. Each summer, its height increases by 1 meter.

A Utopian Tree sapling with a height of 1 meter is planted at the onset of spring. How tall will the tree be after n growth cycles?

For example, if the number of growth cycles is n = 5, the calculations are as follows:

image.png

Function Description

Complete the utopianTree function in the editor below.

utopianTree has the following parameter(s):

  • int n: the number of growth cycles to simulate

Returns

  • int: the height of the tree after the given number of cycles

Input Format

The first line contains an integer, t, the number of test cases. t subsequent lines each contain an integer, n, the number of cycles for that test case.

The second line contains a single word consisting of lowercase English alphabetic letters.

Sample Input 0:

image.png

Sample Output 0:

image.png

Explanation:

There are 3 test cases.

In the first case (n = 0), the initial height (H = 1) of the tree remains unchanged.

In the second case (n = 1), the tree doubles in height and is 2 meters tall after the spring cycle.

In the third case (n = 4), the tree doubles its height in spring (n = 1, H = 2), then grows a meter in summer (n = 2, H = 3), then doubles after the next spring (n = 3, H = 6), and grows another meter after summer (n = 4, H = 7). Thus, at the end of 4 cycles, its height is 7 meters.

I'll get right into the algorithm. Please feel free to read the full question on HackerRank.

Solution πŸ”Ž

In plain English, we have a tree that changes its height after every cycle, n. All that's required is to get the height after a given number of cycles.

Initially, I almost over-engineered this problem, but alas, good old if-else statements sufficedπŸ˜….

Let's write down the steps we'll use to solve this problem.

# Given the growth cycle, n, loop through from n = 1.
# Develop the tree height logic for calculating the respective tree heights
# From the conditional logic, calculate the heights for all cycles 
# Return the height at the last cycle.

Step 1️⃣: Loop through all cycles up to n➿

  1. Since we're not going the math route, we need to calculate the height H for each cycle n.
  2. We'll also track the current height at each cycle with current_height.
def utopianTree(n):
    # Write your code here
    # the tree starts with a default height of 1 at cycle, n = 0
    current_height = 1

    # loop through the cycles starting from 1 since we know cycle 0 gives
    # height of 1 unit.
    # also loop through to n+1 to reach the last cycle.
    for cycle in range(1, n+1):

Step 2️⃣: Develop the tree height's conditional logic 🌴🎲

  1. We'll need conditional statements to determine what changes to the height happen at what cycle.
  2. The 2 changes are a height multiplication by 2, and an increase in height by 1.
  3. You'll also notice a clear pattern from the input periods and their corresponding heights. (I'm fond of patterns😏). image.png

    odd number periods/cycles multiply the tree's height by 2 while even number periods/cycles increment the tree's height by 1

  4. With these, you can easily develop conditional the logic as such:
def utopianTree(n):
    # Write your code here
    # the tree starts with a default height of 1 at cycle, n = 0
    current_height = 1

    # loop through the cycles starting from 1 since we know cycle 0 gives
    # height of 1 unit.
    # also loop through to n+1 to reach the last cycle.
    for cycle in range(1, n+1):

        # the default height for the beginning of the cycles
        # simply return the current height (set to 1 initially)
        if (n == 0) :
            return current_height

        # for the first cycle in the year, the tree's height doubles, hence
        # if this condition is true, it means the period is odd. thereafter 
        # move on to the next cycle 
        elif (cycle % 2) != 0:
            current_height *= 2
            cycle += 1

        # the next cycle is spring, meaning the tree's height increases by 1.
        # all other numbers (even numbers) will satisfy this condition. thereafter
        # move on to the next cycle as usual.
        else:
            current_height += 1
            cycle += 1

Step 3️⃣: Return the tree's current height.

Lastly, we'll simply return current_height.

def utopianTree(n):
    # Write your code here
    # the tree starts with a default height of 1 at cycle, n = 0
    current_height = 1

    # loop through the cycles starting from 1 since we know cycle 0 gives
    # height of 1 unit.
    # also loop through to n+1 to reach the last cycle.
    for cycle in range(1, n+1):

        # the default height for the beginning of the cycles
        # simply return the current height (set to 1 initially)
        if (n == 0) :
            return current_height

        # for the first cycle in the year, the tree's height doubles, hence
        # if this condition is true, it means the period is odd. thereafter 
        # move on to the next cycle 
        elif (cycle % 2) != 0:
            current_height *= 2
            cycle += 1

        # the next cycle is spring, meaning the tree's height increases by 1.
        # all other numbers (even numbers) will satisfy this condition. thereafter
        # move on to the next cycle as usual.
        else:
            current_height += 1
            cycle += 1

    # finally return the current height at the end of all cycles.
    return current_height

utopianTree(5)
#14

That's it! Thanks for reading! πŸ™‚

Hope this article helped with understanding this challenge. Happy Coding!πŸ‘¨πŸ½β€πŸ’»

Buy me a coffee.png

Β