DEV Community

Sivakumar
Sivakumar

Posted on • Updated on

Data Structures & Algorithms using Rust: Two Sum

As part of Data Structures and Algorithms implementation using Rust, today we will explore Two Sum problem.

Leetcode problem link: https://leetcode.com/problems/two-sum/

Problem Statement
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

You can return the answer in any order.
Enter fullscreen mode Exit fullscreen mode
Instructions
Example 1:

Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Output: Because nums[0] + nums[1] == 9, we return [0, 1].
Example 2:

Input: nums = [3,2,4], target = 6
Output: [1,2]
Example 3:

Input: nums = [3,3], target = 6
Output: [0,1]


Constraints:

2 <= nums.length <= 105
-109 <= nums[i] <= 109
-109 <= target <= 109
Only one valid answer exists.
Enter fullscreen mode Exit fullscreen mode
Solution

Please find below the solution implemented using Rust

use std::collections::HashMap;

impl Solution {
    pub fn two_sum(nums: Vec<i32>, target: i32) -> Vec<i32> {
        let l = nums.len();
        let mut m = HashMap::new();
        for i in 0..l {
            let t = target-nums[i];
            if let Some(x) = m.get(&t) {
                return vec![*x, i as i32];
            } else {
                m.insert(nums[i], i as i32);
            }
        }
        vec![]
    }
}
Enter fullscreen mode Exit fullscreen mode
Outcome from Leetcode

Runtime: 0 ms, faster than 100.00% of Rust online submissions for Two Sum.
Memory Usage: 2.5 MB, less than 23.25% of Rust online submissions for Two Sum.

Please feel free to share your feedback.

Happy reading!!!

Top comments (1)

Collapse
 
shahenshah profile image
ShaikShahinsha

Hello>>>Shiva .... can we achieve tagetsum using Set collection of Rust....
Here , i tried with that Set approach..... it returns me empty array.... could you please help me out on this!!!!

fn targetTwoSum(vecval: Vec, tagetSum:i32)-> Vec{
let mut sets: HashSet = HashSet::new();
for i in vecval{
let potential_match = tagetSum - i;

// println!("the potential_match : {}",potential_match);
if let Some(pos) = sets.get(&potential_match){
println!("entering in if");
return vec![i,*pos];
}

sets.insert(potential_match);

}
println!("the set values are : {:?}",sets);
vec![]
Enter fullscreen mode Exit fullscreen mode

}