loading...

Data Structures & Algorithms using Rust: Two Sum

ssivakumar77 profile image Sivakumar Updated on ・1 min read

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!!!

Discussion

pic
Editor guide