Harbor Tide Chants
Think of a small harbor challenge where order and timing really matter. In Harbor Tide Chants, you are trying to work toward the right number by following one clear idea.
Generate harbor tide chant recursively A good way to think about it is to first understand what goes in, then what rule you must follow, and finally what shape the answer should have.
For example, if the input is rolls = 2, the answer is 13. The second roll adds a verse and repeats the earlier chorus three times. Another example is rolls = 0, which gives 1. Only the caller sings, so one verse is heard.
This is a friendly practice problem, but it still rewards careful reading. The key is understanding the rule clearly and then applying it carefully.
One helpful habit is to say the rule out loud in your own words before you start solving. If you can explain what counts, what changes, and what the final answer should look like, you are already much closer to the right solution.
Example Input & Output
The second roll adds a verse and repeats the earlier chorus three times.
Only the caller sings, so one verse is heard.
Four rolls follow the rule, ending with one guiding verse plus triple the sound of roll three.
Algorithm Flow
Solution Approach
This problem is about a growing chant where each roll builds on the previous one. The key is to notice that the total at each step is defined by the total from the step before it, so we can simulate the growth with a simple loop.
The rule is stated clearly in the examples: each new roll adds one verse and repeats the earlier chorus three times. In other words, the new total is 1 + 3 * (previous total). We can compute this step by step starting from a single chant.
We keep a running result that starts at 1 (the very first chant), then update it once per roll:
The heart of the solution is the update line result = 1 + 3 * result. Each iteration takes the previous total, multiplies it by 3 (the repeated chorus), and adds 1 for the new verse.
Let us trace rolls = 2. We start with result = 1. After the first iteration, result = 1 + 3 * 1 = 4. After the second iteration, result = 1 + 3 * 4 = 13. That matches the expected answer of 13. When rolls = 0, the loop never runs, so we return 1, which is just the single caller's chant.
This approach is efficient because it only needs rolls steps. The time complexity is O(rolls) and the space complexity is O(1), since we only keep one running value.
Best Answers
class Solution {
public int harbor_tide_chants(int rolls) {
int result = 1;
for (int i = 0; i < rolls; i++) {
result = 1 + 3 * result;
}
return result;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
