DEV Community

Cover image for 1. Two Sum
Lewis Lloyd
Lewis Lloyd

Posted on • Edited on

3

1. Two Sum

Python

Solution walkthrough: https://twitter.com/lloydtao/status/1584288569622790145

🥇 Hash table - O(n)

Method: Take each number and check if its complement has been seen before. If not, add it to the list of known complements along with its index.

  • Time complexity: O(n)
  • Space complexity: O(n)
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        """Take each number and check if its complement has been seen before. If not,
        add it to the list of known complements along with its index.

        Args:
            nums (List[int]): Input array of integers
            target (int): Target integer

        Returns:
            List[int]: Indices of the two integers that sum to target
        """
        # Initialise hash map to store known integers
        complements = {}
        # Iterate through the list
        for i in range(len(nums)):
            # Check if the current number's complement has been seen before
            complement = target - nums[i]
            if complement in complements:
                return [complements[complement], i]
            # Add the current number to the list of known complements
            complements[nums[i]] = i
Enter fullscreen mode Exit fullscreen mode

🥈 Check pairs - O(n²)

Method: Take each pair of numbers and see if they add up to the target.

  • Time complexity: O(n²)
  • Space complexity: O(1)
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        """Take each pair of numbers and see if they add up to the target.

        Args:
            nums (List[int]): Input array of integers
            target (int): Target integer

        Returns:
            List[int]: Indices of the two integers that sum to target
        """
        # Get length of input array
        n = len(nums)
        # Iterate over all pairs (i,j)
        for i in range(n):
            for j in range(i + 1, n):
                # Check if this pair equals the target
                if nums[i] + nums[j] == target:
                    return [i, j]
Enter fullscreen mode Exit fullscreen mode

Image of Datadog

How to Diagram Your Cloud Architecture

Cloud architecture diagrams provide critical visibility into the resources in your environment and how they’re connected. In our latest eBook, AWS Solution Architects Jason Mimick and James Wenzel walk through best practices on how to build effective and professional diagrams.

Download the Free eBook

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay