DEV Community

Ertugrul
Ertugrul

Posted on

πŸ—“ Daily LeetCode Progress – Day 10

Problems Solved:

  • #4 Median of Two Sorted Arrays
  • #20 Valid Parentheses

This continues my daily series (Day 10: Sorting + Stack patterns). Hitting a 10‑day streak 🎯 feels great β€” the 5/10/15 day checkpoints help me keep momentum and show consistent practice.


πŸ’‘ What I Learned

Today’s focus was on two fundamentals:

  • For Median of Two Sorted Arrays, I implemented the straightforward merge‑then‑sort approach for clarity. It’s not the optimal O(log(m+n)) partition method, but it’s clean and correct. In C++, I also guarded against overflow by promoting to long long before averaging.
  • For Valid Parentheses, the classic stack trick: push the expected closing bracket when you see an opener; on any closer, check the stack top for a match or fail fast.

🧩 #4 β€” Median of Two Sorted Arrays

Python (Sort & pick middle)

class Solution:
    def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
        nums3 = sorted(nums1 + nums2)
        n = len(nums3)
        if len(nums3) % 2 == 1:
            return float(nums3[n // 2])
        else:
            return (nums3[n // 2 - 1] + nums3[n // 2]) / 2
Enter fullscreen mode Exit fullscreen mode

Why it works: Concatenate, sort, and take the middle(s). It’s the simplest correct approach; great for readability and quick validation.

Time: O((m+n)Β·log(m+n))
Space: O(m+n) (new merged list)

C++ (In‑place merge & safe average)

class Solution {
public:
    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
        nums1.insert(nums1.end(), nums2.begin(), nums2.end());
        sort(nums1.begin(), nums1.end());
        int n = (int)nums1.size();
        if (n % 2 == 1) {
            return static_cast<double>(nums1[n/2]);
        } else {
            long long a = nums1[n/2 - 1];
            long long b = nums1[n/2];
            return (a + b) / 2.0;
        }
    }
};
Enter fullscreen mode Exit fullscreen mode

Why it works: Same idea as Python. Using long long prevents overflow on the sum before dividing by 2.0.

Time: O((m+n)Β·log(m+n))
Space: O(1) extra (reuses nums1’s buffer after insert)

Note: The optimal approach is the partition method with binary search on the smaller array to achieve O(log(m+n)). I stuck to the clear version today to keep the streak focused on fundamentals.


🧩 #20 β€” Valid Parentheses

Python (Expected‑closer stack)

class Solution:
    def isValid(self, s: str) -> bool:
        stack = []
        for ch in s:
            if ch == '(':
                stack.append(')')
            elif ch == '{':
                stack.append('}')
            elif ch == '[':
                stack.append(']')
            elif not stack or stack.pop() != ch:
                return False
        return not stack
Enter fullscreen mode Exit fullscreen mode

Why it works: Push the expected closing bracket for each opener. On a closer, pop and compare. Any mismatch or early closer fails.

Time: O(n)
Space: O(n)

C++ (Top‑then‑pop)

class Solution {
public:
    bool isValid(string s) {
        stack<char> st;
        for (char c : s) {
            if (c == '(') {
                st.push(')');
            } else if (c == '{') {
                st.push('}');
            } else if (c == '[') {
                st.push(']');
            } else {
                if (st.empty() || st.top() != c) return false;
                st.pop();
            }
        }
        return st.empty();
    }
};
Enter fullscreen mode Exit fullscreen mode

Why it works: Identical logic as Python. Always check top() before pop(); pop() doesn’t return a value.

Time: O(n)
Space: O(n)


πŸ“Έ Achievements

  • Median of Two Sorted Arrays: Python & C++ implementations validated.

Median python

Median cpp

  • Valid Parentheses: Stack pattern implemented in both languages with edge‑case handling (empty, early closers, leftover openers).

valid python

valid cpp


πŸ“¦ Complexity Recap

  • Median of Two Sorted Arrays: O((m+n)Β·log(m+n)) time; Python space O(m+n), C++ extra space O(1) after merge.
  • Valid Parentheses: O(n) time, O(n) space.

πŸ“£ Join the Journey

Day 10 streak βœ… and counting! I’m solving and documenting problems daily in both Python and C++, highlighting patterns and performance insights. Follow along if you’re into algorithms and clean, reliable implementations.

Links

Top comments (0)