LeetCode with Corgis and Kittens — Solving the Two Sum Problem!!!
LeetCode with Corgis Comic GIF 🎁 Issue #1 — Two Sum
Hello 👋💻🌎 Tech World,
LeetCode with Corgis and Kittens Problem #1 — Two Sum
MAKING LEARNING HOW TO CODE
✧・゚:* CUTE(◕‿◕✿) and INFORMATIVEᕙ(⇀‸↼‶)ᕗ!!!
See repo below this comic. Hope you enjoy it!
Problem Statement
Given an array of integers, return indices of the 2️⃣ numbers such that they add up to a specific target 🎯.
You may assume that each input would have exactly one solution, and you may not use the same item twice.
Example:
Given nums = [2, 11, 7, 15], target🎯 = 9,
Because nums[0] + nums[2] = 2 + 7 = 9,return [0, 2].
Two Sum Animation
Approach 1: Brute Force
Java☕
JavaScript💛
Python 🐍
Complexity Analysis — Brute Force Approach:
- Time complexity ⏰: O(n²). For each number🔢, we try to find its difference/complement by looping through the rest of the list of numbers🔢 which takes O(n) time. Therefore, the Time Complexity is O(n²).
- Space complexity🚀: O(1).
Approach 2: Two-pass [HashTable/Object/Dictionary]
Step 1. Create a Hash Map/Object/Dictionary
Step 2. Loop through and check if the target value — nums[index] is in the dictionary
Java☕
JavaScript💛
Python 🐍
Complexity Analysis — Two-Pass Approach:
- Time complexity ⏰: O(n) We go through the list of n numbers exactly twice. Using the [hash table☕/dictionary🐍/object💛] reduces the lookup time to O(1), the Time Complexity is O(n).
- Space complexity🚀: O(n). The extra space required depends on the number of items stored in the [hash table☕/dictionary🐍/object💛] which stores exactly n numbers.
Approach 3: One-pass [Hash Table/Object/Dictionary]
Java☕
JavaScript💛
Python 🐍
Complexity Analysis — One Pass Approach:
- Time complexity ⏰: O(n). We traverse the list containing n numbers🔢 only once. Each lookup in the table costs only O(1) time.
- Space complexity🚀: O(n). The extra space required depends on the number of items stored in the [hash table☕/dictionary🐍/object💛], which stores at most n numbers🔢.
Thank you for reading ❤,
Kodie The Coding Corgi & Bits The A.I.
P.S. If this comic strip was able to help you in any way, sign up for our newsletter it means a lot and to send your thoughts and feelings about this work. DM us on Instagram or tweet us on Twitter. Please share this with your coding friends, corgis friends, and coding corgis friends so we can make more comics in the future with your support. Thank You!