Sitemap
Tech Panda

Tech Panda

Senior Software Engineer @MAANG. Follow me for more tech interviews, skills, and career advice.

Member-only story

Algo Interview Prep 1: Two Sum (Easy)

3 min readOct 17, 2022

--

Questions

Given an array of integers nums and an integer, return indices of the two numbers such that they add up to target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

You can return the answer in any order.

Example 1:

Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].

Example 2:

Input: nums = [3,2,4], target = 6
Output: [1,2]

Example 3:

Input: nums = [3,3], target = 6
Output: [0,1]

Analysis

Approach 1: Brute Force

The brute force approach is simple. Loop through each element and find if another value equals to target.

class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[j] == target - nums[i]:
return [i, j]

Complexity Analysis

  • Time complexity: O(n²)O(n2). For each element, we try to find its complement by looping through the rest of the array, which takes O(n)O(n) time. Therefore, the time complexity is O(n²)O(n2).
  • Space complexity: O(1)O(1). The space required…

--

--

Tech Panda
Tech Panda

Written by Tech Panda

Senior Software Engineer @MAANG. Follow me for more tech interviews, skills, and career advice.