Two Sum — Asked in Facebook, Google, and Amazon Interviews

Problem Statement :

You are given an array of integers of length ’n’ and an integer ‘x’. Your task is to return a pair of elements such that they add up to ‘Target’.

The first line contains two integers, integer ’n’, denoting the number of elements, and integer ‘x’, denoting the ‘Target’.

The next line contains the array of numbers from where we have to consider the numbers.

Given:

4 92 7 11 13

Output :

7 2

Explanation of given Test Cases :

For the given test case, we can see that the sum of  2 and 7 is equal to 9 and it is the only valid pair.

Approach:

Hashing Solution:

This problem can be solved efficiently by using the technique of hashing. Use a hash_map to check for the current array value x(let). If there exists a value target_sum - x, which on adding to the former gives, target_sum, print out that value pair.

This can be done in constant time.

Code:

Time Complexity : O(N)
Space Complexity : O(N)

Thanks for Reading

Placewit grows the best engineers by providing an interactive classroom experience and by helping them develop their skills and get placed in amazing companies.

Learn more at Placewit. Follow us on Instagram and Facebook for daily learning.

--

--

--

Upskilling students for tech placements!

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Agoda Clone

Helidon Extension for Visual Studio Code

The modern flows of connectivity — API Gateways and Service Meshes

SPOF: Deactivating a future problem, now

6 metrics for HTTP file extraction

How to Enable Transparent Data Encryption on Alibaba Cloud

PostgreSQL Data Rotate Method Introduction: Overwrite History Data by Time

Making a Post API in Laravels

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Placewit

Placewit

Upskilling students for tech placements!

More from Medium

Longest Increasing Subsequence Coding Question

Leetcode 1642. Furthest Building You Can Reach

Interviewing Experience with PayPay Japan

Meta / Amazon / Google / Microsoft Interview Question: Wildcard Matching Solution | LeetCode-44…