🌟 Day 84 of My #100DaysOfCode Challenge 🧩 Problem: LeetCode 108 – Convert Sorted Array to Binary Search Tree 💭 Understanding the Problem Given a sorted array, we need to convert it into a height-balanced Binary Search Tree (BST) — meaning the difference in height between the left and right subtrees of every node should not exceed one. 📘 Example: Input: nums = [-10, -3, 0, 5, 9] Output: [0, -3, 9, -10, null, 5] The middle element (0) becomes the root, left half forms the left subtree, and the right half forms the right subtree. 🧠 Key Idea Pick the middle element as the root for balance. Recursively repeat the same for left and right halves. This approach ensures that the BST remains balanced. ⚙️ Complexity Analysis Time Complexity: O(n) — each element is processed once. Space Complexity: O(log n) — recursion stack in a balanced tree. ✨ Takeaway This problem beautifully combines recursion and binary tree logic, showcasing how dividing the array strategically helps maintain balance in a BST. 💬 "Balanced structures are key to efficiency — both in code and in life!" 😄 #Day84 #LeetCode #Java #DSA #BinaryTree #CodingChallenge #100DaysOfCode #ProblemSolving
Converting Sorted Array to Balanced BST in 100 Days of Code
More Relevant Posts
-
✅Day 41 : Leetcode 153 - Find Minimum in Rotated Sorted Array #60DayOfLeetcodeChallenge 🧩 Problem Statement Given a sorted array that has been rotated at an unknown pivot, find the minimum element in the array. The array contains unique elements, and the solution must run in O(log n) time. 💡 My Approach I used a binary search technique to efficiently find the minimum element. I maintained two pointers, low and high. At each step, I calculated the mid-point. If the left part (nums[low] to nums[mid]) was sorted, I updated my answer with the smaller of nums[low] and current ans, and moved low to mid + 1. Otherwise, I updated my answer with nums[mid] and moved high to mid - 1. This approach ensures we keep narrowing the search space toward the minimum element. ⏱️ Time Complexity O(log n) — Because the search space is halved in each iteration. #BinarySearch #LeetCode #RotatedSortedArray #DSA #CodingPractice #Java #ProblemSolving
To view or add a comment, sign in
-
-
📌 Day 15/100 - Majority Element (LeetCode 169) 🔹 Problem: Given an array of integers nums, find the element that appears more than ⌊ n/2 ⌋ times — the majority element. It’s guaranteed that such an element always exists in the array. 🔹 Approach: Implemented the Boyer–Moore Voting Algorithm, a clever and efficient approach: Assume the first element as the candidate. Traverse the array — increment votes if the element matches the candidate, otherwise decrement. If votes reach zero, update the candidate. The last candidate standing is the majority element. 🔹 Time Complexity: O(n) — only one traversal through the array. 🔹 Space Complexity: O(1) — uses constant extra space. 🔹 Key Learnings: Learned how voting logic simplifies counting-heavy problems. Achieved 99.76% faster runtime on LeetCode. Reinforced how simplicity and logic often outperform brute force. 💡 Every dataset has a voice — you just need the right logic to hear it. #100DaysOfCode #LeetCode #Java #ProblemSolving #DSA #CodingChallenge #BoyerMooreAlgorithm
To view or add a comment, sign in
-
-
🧠 LeetCode Day 97 — Path Sum (Problem 112) Today’s challenge was about checking whether a binary tree has a root-to-leaf path such that adding up all the values along the path equals a given sum. 🔍 Problem Description: Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that the sum of the node values equals targetSum. Otherwise, return false. 💡 Approach: Traverse the tree recursively. Subtract the current node’s value from targetSum. When a leaf node is reached, check if the remaining sum equals zero. Use Depth First Search (DFS) to explore all paths. 🚀 Key Learnings: Strengthened understanding of recursive tree traversal. Practiced handling base cases in recursion effectively. Improved clarity on root-to-leaf path logic in binary trees. 🌳 #Day97 of #100DaysOfCode Each challenge adds a new layer to my problem-solving skills. Binary tree problems like this sharpen the recursive mindset — thinking from root to leaf and back up! 💪 #LeetCode #CodingChallenge #Java #100DaysOfCode #BinaryTree #ProblemSolving #Recursion
To view or add a comment, sign in
-
-
💻 Day 34 — LeetCode 912: Sort an Array (Merge Sort Implementation) Today, I learned and implemented Merge Sort, a classic Divide and Conquer algorithm that efficiently sorts arrays with a time complexity of O(n log n). I applied it to LeetCode 912 (Sort an Array) — where the task is to sort an integer array without using built-in sorting methods. This problem helped me understand: How recursion splits the array into halves How merging combines sorted halves Why Merge Sort guarantees stable and consistent performance 🧠 Key takeaway: Merge Sort ensures O(n log n) in all cases (best, average, and worst), making it one of the most reliable sorting algorithms. #LeetCode #Day34 #DSA #SortingAlgorithms #MergeSort #CodingJourney #Java #ProblemSolving
To view or add a comment, sign in
-
-
🚀 Day 87/100 of #100DaysOfCode 💡 Problem: 3321. Find X-Sum of All K-Long Subarrays II (Hard) 🔗 Platform: LeetCode Today’s challenge was all about optimizing sliding window logic with frequency-based ordering! The task — find the “x-sum” of every k-sized subarray, keeping only the top x most frequent elements (and if tied, prefer larger values). 🧠 Key Learnings: How to maintain frequency counts efficiently in a sliding window. Managing top-x elements dynamically using TreeSet and custom comparators. Overcoming TLE issues by switching from naive sorting (O(n*k)) to a balanced TreeSet approach (O(n log n)). ⚙️ Concepts Used: → Sliding Window → Frequency Map (HashMap) → Ordered Sets (TreeSet) → Custom Comparator Logic 🔥 This one really tested both logic & optimization — but once it clicked, it felt amazing! #LeetCode #100DaysOfCode #Java #CodingChallenge #ProblemSolving #DSA #SlidingWindow #Optimization
To view or add a comment, sign in
-
-
✅ Day 51 of LeetCode Medium/Hard Edition Today’s challenge was about generating numbers whose prime factors are limited to 2, 3, and 5 — the classic Ugly Number II problem! 💫 📦 Problem: An ugly number is a positive integer whose prime factors are restricted to 2, 3, and 5. Given an integer n, return the nth ugly number. 🔗 Problem Link: https://lnkd.in/gS9EKbbd ✅ My Submission: https://lnkd.in/gnTe_zvY 💡 Thought Process: To generate the sequence in ascending order, we can use a Min-Heap + HashSet approach: Start from 1, the first ugly number. Repeatedly multiply it by {2, 3, 5} to generate new candidates. Maintain a min-heap to always pick the next smallest number. Use a set to avoid duplicates. After popping n elements, the last popped value is our nth ugly number. ⏱ Complexity: Time: O(n log n) Space: O(n) 🔥 Key Takeaway: Combining heaps and hashing efficiently maintains order and uniqueness in sequence generation. A great demonstration of how priority queues can systematically build ordered numeric sequences — step by step! #LeetCodeMediumHardEdition #100DaysChallenge #Heap #HashSet #ProblemSolving #DataStructures #CodingJourney #Java #LeetCode
To view or add a comment, sign in
-
-
💻 Day 59 of #100DaysOfCode Challenge 🚀 Today's problem: Leetcode 240 – Search a 2D Matrix II 🔍 This problem was about efficiently searching for a target value in a 2D matrix where each row and each column is sorted in ascending order. 💡 Key Insight: Instead of searching the entire matrix, start from the top-right corner: If the current element is greater than the target → move left. If it’s smaller → move down. This approach ensures that we eliminate one row or one column in every step — achieving O(m + n) time complexity. 📊 Result: ✅ Accepted – All test cases passed successfully! ⚡ Time Complexity: O(m + n) 💾 Space Complexity: O(1) 🧠 Takeaway: This problem was a great reminder that understanding data structure properties can help you find smarter solutions rather than brute-forcing through the problem. Every problem adds another brick to the foundation of logical thinking and algorithmic mastery. 💪 #Day59 #LeetCode #Java #ProblemSolving #CodingChallenge #100DaysOfCode #TechLearning #DSA
To view or add a comment, sign in
-
#Day_34 Today’s problem was a satisfying one to solve — “Single Element in a Sorted Array” 🔍 Given a sorted array where every element appears twice except for one unique element, the task is to identify that single element. At first, it seems like a simple linear scan could do the job — and yes, it can. But I focused on building a clean and logical O(n) approach before thinking about optimization 🧠 Approach We observe that: Every element appears in pairs, and because the array is sorted, duplicates are adjacent. The unique element is the only one that doesn’t match its left or right neighbor. We can handle three cases: First element: If it’s not equal to the next one → it’s the single element. Last element: If it’s not equal to the previous one → it’s the single element. Middle elements: If an element is different from both its previous and next → that’s our answer. This way, we can detect the single element in just one pass through the array ⏱ Complexity Time: O(n) — We traverse the array once. Space: O(1) — No extra memory used. 💬 Reflection This problem is a good reminder that not every efficient solution has to start complex. Sometimes, the cleanest brute-force version gives a perfect foundation for further optimization — in this case, even leading to an O(log n) binary search variant. Each problem in this challenge pushes me to think deeper about patterns, structure, and clarity in problem-solving. #CodingJourney #LeetCode #ProblemSolving #100DaysOfCode #Java #LearnByDoing #DSA
To view or add a comment, sign in
-
-
#100DaysOfCode – Day 81 Linked List Cycle Problem Given the head of a linked list, determine whether the list contains a cycle meaning a node’s next pointer refers back to a previous node. My Approach Used Floyd’s Cycle Detection Algorithm (Tortoise & Hare Method): Initialized two pointers slow and fast. Moved slow one step and fast two steps in each iteration. If they ever meet → cycle detected. If fast or fast.next becomes null → no cycle exists. Complexity Time: O(n) Space: O(1) Even in problems involving dynamic structures like linked lists, a simple pointer-based approach can lead to an elegant and optimal solution. #100DaysOfCode #LeetCode #Java #ProblemSolving #DataStructures #LinkedList #TortoiseAndHare #takeUforward #CodeNewbie #CodingJourney
To view or add a comment, sign in
-
-
✅Day 54 : Leetcode 3228 - Maximum Number of Operations to Move Ones to the End #60DayOfLeetcodeChallenge 🧩 Problem Statement You are given a binary string s. You can perform the following operation any number of times: Choose an index i such that: i + 1 < s.length s[i] == '1' s[i+1] == '0' Then move this '1' to the right until it reaches the next '1' or the end of the string. Your task is to return the maximum number of such operations that can be performed. ✅ My Approach Instead of simulating every movement (which is slow), I used a counting strategy: 🔹 Key Idea Whenever I see a '1', I increase the count of ones seen so far. Whenever I see a pattern like …10…, this '1' can move past all previous ones, contributing extra operations equal to the number of '1's before it. 🔹 Steps Initialize: ones = 0 → counts how many '1' encountered so far. res = 0 → stores total operations. Traverse the string: If current char is '1' → increment ones. Else if the previous char is '1' (meaning we found 10) → add ones to result. Return res as the maximum operations. This avoids simulation and gives the optimal count directly. ⏱ Time Complexity O(n) — Single scan through the string O(1) space #dsa #leetcode #binarysearch #java #coding #problemsolving #100daysofdsa #interviewpreparation #learningeveryday #codingjourney
To view or add a comment, sign in
-
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development