Skip to content

Add Two Sum solution in Java (kumar1593#12)#15

Open
maitriupadhyay03-cell wants to merge 2 commits into
kumar1593:mainfrom
maitriupadhyay03-cell:feature-two-sum-12
Open

Add Two Sum solution in Java (kumar1593#12)#15
maitriupadhyay03-cell wants to merge 2 commits into
kumar1593:mainfrom
maitriupadhyay03-cell:feature-two-sum-12

Conversation

@maitriupadhyay03-cell

Copy link
Copy Markdown

Closes #12

Summary

This PR adds a Two Sum solution in Java to the Arrays section.

Problem

Given an array of integers and a target, return indices of the two numbers that add up to the target.

Approach

HashMap-based single-pass solution:

  • For each element, check if (target - element) is already in the map
    • If found, return both indices
    • Otherwise, store the element and its index

Complexity

  • Time: O(n)
    • Space: O(n)

Test Cases

  • [2,7,11,15], target=9 → [0,1]
    • [3,2,4], target=6 → [1,2]
    • [3,3], target=6 → [0,1]

Implement Two Sum problem using HashMap for efficient lookup.
Renamed two_sum.java to TwoSum.java and updated the public class name from 'two_sum' to 'TwoSum' to follow standard Java PascalCase naming conventions. Also updated the instantiation in main() accordingly.
@maitriupadhyay03-cell

Copy link
Copy Markdown
Author

Fix applied: Renamed two_sum.javaTwoSum.java and updated the public class name from two_sum to TwoSum to follow standard Java PascalCase naming conventions. Also updated the object instantiation in main() accordingly. The logic remains unchanged.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add More DSA Problems to Repository

1 participant