UrbanPro
true
default_background

Take BTech Tuition from the Best Tutors

  • Affordable fees
  • 1-1 or Group class
  • Flexible Timings
  • Verified Tutors
✕

Search in

DSA for Placements: Two Sum – From Brute Force to Optimized Solutions

Profile Photo Tanmoy Gupta
9 mins ago 0 View Comments0

DSA for Placements: Two Sum – From Brute Force to Optimised Solutions

1. Introduction

Solving a programming problem is not just about writing code. In technical interviews, recruiters want to understand how you approach a problem, analyse possible solutions and optimise your algorithm.

Let's explore one popular DSA interview problem: Two Sum.

2. Problem Statement

Given an integer array and a target value, find the indices of two distinct elements whose sum equals the target.

Example:

Array = [2, 7, 11, 15]

Target = 9

Expected Output = [0, 1]

Explanation: Array[0] + Array[1] = 2 + 7 = 9.

3. Approach 1: Brute Force

The simplest approach is to compare every possible pair of elements.

Python implementation:

def two_sum(nums, target):
    for i in range(len(nums)):
        for j in range(i + 1, len(nums)):
            if nums[i] + nums[j] == target:
                return [i, j]
    return []

print(two_sum([2, 7, 11, 15], 9))

Output:

[0, 1]

Complexity Analysis:

  • Time Complexity: O(n²)

  • Auxiliary Space Complexity: O(1)

The nested loops repeatedly examine pairs of elements. This solution works, but becomes inefficient for large arrays.

4. Approach 2: Optimised Solution Using HashMap

Can we avoid checking every possible pair?

Yes!

For each element x, calculate:

Complement = Target − x

Instead of searching the remaining array repeatedly, store previously visited elements in a HashMap.

Python implementation:

def two_sum(nums, target):
    seen = {}

    for i, num in enumerate(nums):
        complement = target - num

        if complement in seen:
            return [seen[complement], i]

        seen[num] = i

    return []

print(two_sum([2, 7, 11, 15], 9))

Output:

[0, 1]

5. Dry Run of the Optimised Algorithm

Array = [2, 7, 11, 15]

Target = 9

Index Current Complement Decision
0 2 7 Not found; store 2 → 0
1 7 2 Found! Return [0, 1]

The algorithm stops as soon as the required pair is identified.

6. Complexity Comparison

Parameter Brute Force HashMap
Time O(n²) O(n) average
Auxiliary Space O(1) O(n)

The optimised solution trades additional memory for faster searching.

Important interview point: Check for the complement before inserting the current element into the HashMap. This prevents using the same array element twice and correctly handles duplicates such as [3, 3], target = 6.

7. What Does an Interviewer Expect?

When solving a DSA problem, practise the following sequence:

  1. Understand the problem and constraints.

  2. Identify edge cases.

  3. Explain the brute-force approach.

  4. Analyse its time and space complexity.

  5. Identify the opportunity for optimisation.

  6. Write the optimised code.

  7. Explain the complexity and test the solution.

Remember: A good candidate explains the reasoning, not just the final code.


Continue Your Placement Preparation

This problem is a small introduction to the problem-solving approach used in technical interviews.

The 50-Hour Placement Accelerator Programme is designed to develop structured DSA learning, algorithmic thinking, coding practice, complexity analysis and interview problem-solving skills for final-year BTech and MCA students.

Interested in preparing for technical placements?

Explore my UrbanPro teaching profile and enquire about the Placement Accelerator Programme.

Learn to think. Learn to optimise. Prepare to solve.

0 Dislike
Follow 1 Loading Spinner
Default Profile Photo

Please Enter a comment

Submit

Other Lessons for You

The Evolution Of The Intel x86 Architecture
Throughout this book, we rely on many concrete examples of computer design and implementation to illustrate concepts and to illuminate trade-offs. Most of the time, the book relies on examples from two...
Profile Photo

Radiation Pattern
A radiation pattern (or field pattern) is a graph that describes the relative far field value, E or H, with direction at a fixed distance from the antenna. A field pattern includes an magnitude pattern...
Profile Photo

Tips while solving LPP using Simplex Method
1. Delta j under unit column are always zero. 2. Calculate z while doing row operations. 3 in regular simplex method, in initial table delta j are the negative of Cj. So there is no need to calculate...
Profile Photo

Semiconductor
Intrinsic Semiconductor :It is a pure Semiconductor which acts as an insulator at low temperature and acts as a Conductor at high temperature. Hence it is not used in developing electronic devices. Doping:...
Profile Photo

FBD : Free Body Diagram (Mechanical Engineering)
Free body diagram is the graphical representation of forces (Action and Reaction) acting on isolated body or any objects. it is very basic and most useful concept to solve any structural probleme (can...
Profile Photo
X

Looking for BTech Tuition Classes?

The best tutors for BTech Tuition Classes are on UrbanPro

  • Select the best Tutor
  • Book & Attend a Free Demo
  • Pay and start Learning

Take BTech Tuition with the Best Tutors

The best Tutors for BTech Tuition Classes are on UrbanPro

This website uses cookies

We use cookies to improve user experience. Choose what cookies you allow us to use. You can read more about our Cookie Policy in our Privacy Policy

Accept All
Decline All

UrbanPro.com is India's largest network of most trusted tutors and institutes. Over 55 lakh students rely on UrbanPro.com, to fulfill their learning requirements across 1,000+ categories. Using UrbanPro.com, parents, and students can compare multiple Tutors and Institutes and choose the one that best suits their requirements. More than 7.5 lakh verified Tutors and Institutes are helping millions of students every day and growing their tutoring business on UrbanPro.com. Whether you are looking for a tutor to learn mathematics, a German language trainer to brush up your German language skills or an institute to upgrade your IT skills, we have got the best selection of Tutors and Training Institutes for you. Read more