Back to articles
CA 04 - Two Sum & Sorted Two Sum

CA 04 - Two Sum & Sorted Two Sum

via Dev.toSuruthika

TWO SUM PROBLEM I solved the Two Sum problem from LeetCode in java using brute force method. The problem gives an array of integers and a target value. I need to find two indices so that the numbers at those indices add to the target. and i can't use the same element twice, and there will always be one valid answer. To solve this, I used a simple method. I took one number from the array and compared it with every number that comes after it. For every pair i checked if their sum is equal to the target. If it is i need to return the indices of those two numbers. I used two loops for this. The first loop picks one number, and the second loop checks the remaining numbers. As soon as it find a pair that matches the target, it return the answer. This method works correctly but takes more time because it checks all pairs. The time complexity is O(n^2). The space complexity is O(1) because no extra space is used. class Solution { public int [] twoSum ( int [] nums , int target ) { for ( int i

Continue reading on Dev.to

Opens in a new tab

Read Full Article
5 views

Related Articles