Decoding LeetCode: Climbing Stairs & Fibonacci Number Solutions

✳️Day 13 of #100DaysOfCode✳️ Decoding the Logic: Two Problems, One Core Strategy I recently cleared Climbing Stairs and Fibonacci Number on LeetCode with 0ms runtime. 1️⃣ Climbing Stairs (LeetCode 70) The Problem: You are climbing a staircase. It takes n steps to reach the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? The Approach: Recursive Insight: To reach the n^{th} step, you must have come from either the (n-1)^{th} step (by taking 1 step) or the (n-2)^{th} step (by taking 2 steps). Base Cases: * If n = 0 or n = 1, there is only 1 way to be there. The Formula: Ways(n) = Ways(n-1) + Ways(n-2). 2️⃣ Fibonacci Number (LeetCode 509) The Problem: Calculate F(n), where F(n) = F(n-1) + F(n-2) for n > 1, with F(0) = 0 and F(1) = 1. The Approach: Recursive Insight: This is the "pure" mathematical version of the stairs problem. Each number is the sum of the two preceding ones. Base Cases: If n = 0, return 0. If n = 1, return 1. 🚀 Why the 0ms Runtime? In both solutions, I used Top-Down Memoization: The Problem with Simple Recursion: Without optimization, the computer recalculates the same values (like f(5)) dozens of times, leading to an exponential time complexity of O(2^n). The Memoization Fix: I introduced an array dp[]. Before calculating f(n), the code checks: "Have I solved this before?" If dp[n] is not 0, it returns the stored value instantly. If not, it calculates it once, stores it, and moves on. The Result: This simple "memory" trick brings the complexity down to O(n) linear time, making the execution nearly instantaneous. #DataStructures #Algorithms #Java #DP #SoftwareDevelopment #LeetCode

To view or add a comment, sign in

Explore content categories