Shashi Singh’s Post

💡 LeetCode Learning Log — Two Sum II (Input Array is Sorted) 🔗 Problem: https://lnkd.in/gkcqGnfD Today I explored three different approaches to solve this problem: 1️⃣ 𝗕𝗿𝘂𝘁𝗲 𝗙𝗼𝗿𝗰𝗲 𝗔𝗽𝗽𝗿𝗼𝗮𝗰𝗵 • Checked all possible pairs using nested loops. • 𝗧𝗶𝗺𝗲 𝗖𝗼𝗺𝗽𝗹𝗲𝘅𝗶𝘁𝘆: O(n²) 𝗦𝗽𝗮𝗰𝗲: O(1) • Simple but inefficient for large inputs. 2️⃣ 𝗕𝗲𝘁𝘁𝗲𝗿 𝗔𝗽𝗽𝗿𝗼𝗮𝗰𝗵 (𝗨𝘀𝗶𝗻𝗴 𝗛𝗮𝘀𝗵𝗠𝗮𝗽) • Stored elements in a map while traversing. • For every number, checked if (𝘵𝘢𝘳𝘨𝘦𝘵 - 𝘯𝘶𝘮) exists. • 𝗧𝗶𝗺𝗲 𝗖𝗼𝗺𝗽𝗹𝗲𝘅𝗶𝘁𝘆: O(n) 𝗦𝗽𝗮𝗰𝗲: O(n) • Much faster, but takes extra space. • Great when index matters — because it keeps track of original positions. 3️⃣ 𝗢𝗽𝘁𝗶𝗺𝗮𝗹 𝗔𝗽𝗽𝗿𝗼𝗮𝗰𝗵 (𝗧𝘄𝗼 𝗣𝗼𝗶𝗻𝘁𝗲𝗿𝘀) • Since the array is sorted, used two pointers from both ends. • Moved pointers based on the sum comparison. • 𝗧𝗶𝗺𝗲 𝗖𝗼𝗺𝗽𝗹𝗲𝘅𝗶𝘁𝘆: O(n) 𝗦𝗽𝗮𝗰𝗲: O(1) • Clean, elegant, and efficient. 𝗥𝗲𝘀𝘂𝗹𝘁: ✅ All 24 test cases passed ⏱ Runtime: 4 ms 💾 Memory: 12.77 MB 𝗞𝗲𝘆 𝗟𝗲𝗮𝗿𝗻𝗶𝗻𝗴𝘀: • Understand why 𝘁𝘄𝗼 𝗽𝗼𝗶𝗻𝘁𝗲𝗿𝘀 shine when arrays are sorted. • When 𝗶𝗻𝗱𝗲𝘅 𝗽𝗼𝘀𝗶𝘁𝗶𝗼𝗻𝘀 𝗮𝗿𝗲 𝗶𝗺𝗽𝗼𝗿𝘁𝗮𝗻𝘁, sorting may not work. • Don’t just solve, explore multiple approaches to strengthen problem-solving intuition. #LeetCode #DSA #ProblemSolving #Python #TwoPointers #CodingJourney #DataEngineer #100DaysOfCode

  • graphical user interface, text

Keep it up Shashi Singh 😇 Looking forward to see you solving tries like smooth as cake cutting.

Like
Reply

To view or add a comment, sign in

Explore content categories