📅Day 0 of Understanding Time & Space Complexity for Developers: Strivers SDE Sheet Using Java

Payal KumariPayal Kumari
8 min read

Note : I’ve officially started my 27-day DSA journey using Striver’s SDE Sheet. Over the next few weeks, I’ll be journaling my progress daily — breaking down brute-force to optimal solutions, writing clean Java code, analyzing time and space complexity, and sharing key patterns that every aspiring software engineer should master.

This blog series is for anyone preparing for coding interviews — whether you’re a beginner or a revision warrior. Let’s grow together! 🚀

Namaste Developers! 🙏

This blog marks Day 0 of my Striver’s SDE Sheet journey — and I wanted to begin by strengthening one of the most essential (but often overlooked) topics:

(Hindi : "Code likhna easy hai, lekin efficient code likhna ek art hai."
Time aur Space Complexity yehi efficiency ke artist tools hain.)

If you're like me — you've read about TC/SC before, maybe solved many questions... but kabhi kabhi samajh nahi aata tha.

This blog is my simplified version — with real-life analogies, Java code, and clear-cut interview tips — so you can not just learn it, but remember it forever.

💠 What is Time Complexity?

Time Complexity measures how the time required to run an algorithm increases with the size of the input n.

We don’t measure in seconds or milliseconds. We measure in steps — because steps reflect scalability.

📍Real-Life Analogy:

Imagine distributing answer sheets to students in a classroom.

  • If 1 student takes 2 seconds:
    100 students = 200 seconds → That's O(n) (linear time)

  • If you have a machine that directly finds the middle roll number:
    → That’s O(log n) (binary search)

  • If you check each student against every other (like in bubble sort):
    → That’s O(n²) (quadratic time)

💠 What Input Size Means

In most problems, n refers to:

  • Number of elements in an array

  • Number of nodes in a tree/graph

  • Size of the string

  • Number of operations

So always read the question carefully and identify the variable your time depends on.

💠What is Space Complexity?

Space Complexity tells us how much extra memory is needed by the algorithm to work efficiently.

This includes:

  • Temporary variables

  • Data structures (arrays, hashmaps, stacks)

  • Recursion stack (very important!)

📍Real-Life Analogy: Packing for a Trip

  • You carry only a wallet and phone → O(1)

  • You pack a separate bag for each day → O(n)

  • You put bags inside bags inside more bags → O(n²)

(Hindi : "Jitna zyada memory use karega code, utni zyada space lagegi.")

💠Growth of Time Complexities (Best → Worst)

Big O NotationNameExample
O(1)ConstantAccessing arr[5]
O(log n)LogarithmicBinary Search
O(√n)Square RootChecking for prime factors
O(n)LinearSimple loop through array
O(n log n)Log-linearMerge Sort, Quick Sort (avg)
O(n²)QuadraticNested loops (i, j)
O(n³)Cubic3 nested loops – matrix
O(2ⁿ)ExponentialSubsets, recursion-heavy
O(n!)FactorialPermutations, brute TSP

💠Big O vs Omega vs Theta – What's the Difference?

  • O(n) – Worst Case

  • Ω(n) – Best Case

  • Θ(n) – Average Case

If you're searching for an element in an array:

  • Best case: It's the first element → Ω(1)

  • Worst case: It's the last element → O(n)

  • Average case: Somewhere in the middle → Θ(n)

Interviewers usually care most about worst-case (Big O) — always mention that first.

💠Java Code Examples :

1. Sum of All Elements

public int sumArray(int[] arr) {
    int total = 0;
    for (int num : arr) {
        total += num;
    }
    return total;
}
  • Loop runs n times (where n = length of arr)

  • Each iteration does a constant-time operation: total += num

Time Complexity: O(n)

Because it runs once for every element in the array, You go through each element once

Space Complexity: O(1)

Only 1 variable (total) is used — no extra space based on input size

2. Find a Number in Array

public boolean findNumber(int[] arr, int target) {
    for (int num : arr) {
        if (num == target) return true;
    }
    return false;
}
  • Worst case: You check every element to find the target

  • So again, n operations

Time Complexity: O(n)

Worst case: Element not found after scanning full array

Space Complexity: O(1)

No extra space, just checking values / comparing

3. Brute Force for Duplicates

public boolean hasDuplicate(int[] arr) {
    for (int i = 0; i < arr.length; i++) {
        for (int j = i + 1; j < arr.length; j++) {
            if (arr[i] == arr[j]) return true;
        }
    }
    return false;
}
  • Nested loops: Outer runs n times, inner runs up to n times

  • For every i, we compare with every j > i

Time Complexity: O(n²)

Because you're doing n * n comparisons in worst case

Space Complexity: O(1)

No extra space used

(Hindi : "Do loop ek ke andar ho? Samajh jao ki time double nahi, square ban gaya – O(n²)")

4. Optimal Using HashSet

public boolean hasDuplicate(int[] arr) {
    HashSet<Integer> set = new HashSet<>();
    for (int num : arr) {
        if (set.contains(num)) return true;
        set.add(num);
    }
    return false;
}
  • Every .contains() and .add() is approx O(1) in HashSet (average case)

  • You do that for each element → n operations

Time Complexity: O(n) (average case)

Set operations are constant time, loop runs n times

Space Complexity: O(n)

You may store all n elements in the HashSet

(Hindi: "Agar input bada ho, toh nested loop se bachna. HashMap or Set ka use karo — performance mein farak padta hai!")

5. Recursive Call: Factorial

int factorial(int n) {
    if (n == 0) return 1;
    return n * factorial(n - 1);
}
  • Function calls itself n times

  • Each call waits for the next → uses stack

Time Complexity: O(n)

One call per value down to 0

Space Complexity: O(n)

One stack frame per call — n calls = O(n) space

💠Brute Force vs Optimal: Real DSA Mindset

ApproachTimeSpaceNotes
Brute ForceHighLowEasy but slow
OptimalLowerMaybe HighFast but may use extra space

💠Summary Table:

Code ExampleTime ComplexitySpace ComplexityExplanation
Sum of ArrayO(n)O(1)One loop, no extra space
Find NumberO(n)O(1)Search all elements
Brute DuplicatesO(n²)O(1)Nested loop
Optimal DuplicatesO(n)O(n)One pass + HashSet
Factorial RecursionO(n)O(n)n function calls = n stack frames

📍Rules We Must Remember

🔹 Time Complexity:

PatternTC
Single loopO(n)
Nested loopsO(n²)
Binary SearchO(log n)
Two-pointer / Sliding windowO(n)
Hashing lookupO(1) avg

🔹 Space Complexity:

PatternSC
Constant varsO(1)
Using array/map/setO(n)
Recursive function stackO(n)

📍Final Tip :

✅ If you iterate through each element of an array once, the time complexity is O(n).
✅ If you use nested loops to compare elements, the time complexity increases to O(n²).
✅ If an operation executes only once regardless of input size, it is considered O(1) — constant time.
✅ When using recursion, remember that each function call adds to the call stack, so the space complexity also becomes O(n) in such cases.

🎯 Why This Blog Before Day 1?

Every question in Striver’s SDE Sheet — from Arrays to Graphs — tests how well you optimize time and space.

When you know:

  • How many loops you're running

  • What data you're storing

  • What the scale of the input is

You can predict and improve your solution — which is exactly what top companies look for.

✍️ Final Thoughts

This blog is my foundation checkpoint before jumping into Day 1 of the sheet.

"Code toh sab likhte hain. Jo optimise karta hai — wahi real coder hai."

If you ever forget TC/SC again, bookmark this post.

🙏 Special Thanks

A heartfelt thank you to Rajvikraaditya Sir for creating and sharing such an incredible DSA resource with the community (takeuforward). Your structured approach has made DSA more accessible and less intimidating for thousands of learners like me.

💬 Let’s Connect

If this helped you, do share it with your fellow DSA learners.
Comment with your doubts — I’d love to answer and grow together 🌱

✍️ Payal Kumari 👩‍💻
Officially ready to start my 27-Day DSA Journey with Striver’s Sheet! #dsawithpayal

0
Subscribe to my newsletter

Read articles from Payal Kumari directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Payal Kumari
Payal Kumari

I'm a passionate full-stack developer with a strong foundation in the MERN stack—building and maintaining scalable web applications using React.js, Node.js, and Next.js. My journey in open source began with Hacktoberfest 2023, where I made four impactful pull requests that sparked a love for collaborative coding, global learning, and open knowledge sharing. Since then, I’ve contributed to and mentored projects in top open source programs like GSSoC’24, SSOC’24, and C4GT’24. As a Google Gen AI Exchange Hackathon ’24 Finalist and Google’s Women Techmakers (WTM) Ambassador, I’ve been privileged to support diverse communities in building meaningful tech solutions. My work as a Top 50 Mentor for GSSoC ’24 reflects my commitment to nurturing new talent in tech. Beyond development, I serve as a Student Career Guide, Profile Building Expert & Evangelist at Topmate.io, where I conduct workshops, guide students through resume building and career strategy, and help mentees navigate open source and tech careers. Recognized among the Top 5% of mentors and featured on “Topmate Discover,” I take pride in making mentorship accessible and impactful. My technical voice has also been acknowledged by LinkedIn, where I’ve earned the Top Voice badge seven times in domains like web development, programming, and software engineering. In addition, I hold LinkedIn Golden Badges for Research Skills, Interpersonal Skills, Critical Thinking, and Teamwork—signaling a well-rounded approach to both individual contribution and team collaboration. Graduating with an MCA from Chandigarh University in 2023, I’ve continued to fuel my curiosity by writing technical articles and sharing practical MERN stack insights across platforms. Whether it’s building polished UIs, optimizing backend performance, or guiding a mentee through their first pull request, I’m driven by the power of community and continuous learning. Let’s connect! I'm open to collaborations, mentorship, or building something impactful together. Reach out to me at kumaripayal7488@gmail.com or visit my profile on Topmate.io.