Skip to content

Commit

Permalink
Added rust
Browse files Browse the repository at this point in the history
  • Loading branch information
javadev authored Sep 14, 2024
1 parent 8bc6439 commit 686ed81
Show file tree
Hide file tree
Showing 201 changed files with 7,759 additions and 411 deletions.
822 changes: 411 additions & 411 deletions README.md

Large diffs are not rendered by default.

21 changes: 21 additions & 0 deletions src/main/rust/g0001_0100/s0001_two_sum/Solution.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// #Easy #Top_100_Liked_Questions #Top_Interview_Questions #Array #Hash_Table
// #Data_Structure_I_Day_2_Array #Level_1_Day_13_Hashmap #Udemy_Arrays #Big_O_Time_O(n)_Space_O(n)
// #2024_08_24_Time_0_ms_(100.00%)_Space_2.4_MB_(23.16%)

use std::collections::HashMap;

impl Solution {
pub fn two_sum(numbers: Vec<i32>, target: i32) -> Vec<i32> {
let mut index_map: HashMap<i32, usize> = HashMap::new();

for (i, &num) in numbers.iter().enumerate() {
let required_num = target - num;
if let Some(&index) = index_map.get(&required_num) {
return vec![index as i32, i as i32];
}
index_map.insert(num, i);
}

vec![-1, -1]
}
}
38 changes: 38 additions & 0 deletions src/main/rust/g0001_0100/s0001_two_sum/readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
1\. Two Sum

Easy

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.

**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:**

* <code>2 <= nums.length <= 10<sup>4</sup></code>
* <code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code>
* <code>-10<sup>9</sup> <= target <= 10<sup>9</sup></code>
* **Only one valid answer exists.**

**Follow-up:** Can you come up with an algorithm that is less than <code>O(n<sup>2</sup>) </code>time complexity?
54 changes: 54 additions & 0 deletions src/main/rust/g0001_0100/s0002_add_two_numbers/Solution.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
// #Medium #Top_100_Liked_Questions #Top_Interview_Questions #Math #Linked_List #Recursion
// #Data_Structure_II_Day_10_Linked_List #Programming_Skills_II_Day_15
// #Big_O_Time_O(max(N,M))_Space_O(max(N,M)) #2024_08_24_Time_0_ms_(100.00%)_Space_2.2_MB_(14.25%)

// Definition for singly-linked list.
// #[derive(PartialEq, Eq, Clone, Debug)]
// pub struct ListNode {
// pub val: i32,
// pub next: Option<Box<ListNode>>
// }
//
// impl ListNode {
// #[inline]
// fn new(val: i32) -> Self {
// ListNode {
// next: None,
// val
// }
// }
// }
impl Solution {
pub fn add_two_numbers(
l1: Option<Box<ListNode>>,
l2: Option<Box<ListNode>>
) -> Option<Box<ListNode>> {
let mut p = l1;
let mut q = l2;
let mut dummy_head = Box::new(ListNode::new(0));
let mut curr = &mut dummy_head;
let mut carry = 0;

while p.is_some() || q.is_some() {
let x = p.as_ref().map_or(0, |node| node.val);
let y = q.as_ref().map_or(0, |node| node.val);
let sum = carry + x + y;
carry = sum / 10;
curr.next = Some(Box::new(ListNode::new(sum % 10)));
curr = curr.next.as_mut().unwrap();

if let Some(node) = p {
p = node.next;
}
if let Some(node) = q {
q = node.next;
}
}

if carry > 0 {
curr.next = Some(Box::new(ListNode::new(carry)));
}

dummy_head.next
}
}
35 changes: 35 additions & 0 deletions src/main/rust/g0001_0100/s0002_add_two_numbers/readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
2\. Add Two Numbers

Medium

You are given two **non-empty** linked lists representing two non-negative integers. The digits are stored in **reverse order**, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

**Example 1:**

![](https://assets.leetcode.com/uploads/2020/10/02/addtwonumber1.jpg)

**Input:** l1 = [2,4,3], l2 = [5,6,4]

**Output:** [7,0,8]

**Explanation:** 342 + 465 = 807.

**Example 2:**

**Input:** l1 = [0], l2 = [0]

**Output:** [0]

**Example 3:**

**Input:** l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]

**Output:** [8,9,9,9,0,0,0,1]

**Constraints:**

* The number of nodes in each linked list is in the range `[1, 100]`.
* `0 <= Node.val <= 9`
* It is guaranteed that the list represents a number that does not have leading zeros.
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
// #Medium #Top_100_Liked_Questions #Top_Interview_Questions #String #Hash_Table #Sliding_Window
// #Algorithm_I_Day_6_Sliding_Window #Level_2_Day_14_Sliding_Window/Two_Pointer #Udemy_Strings
// #Big_O_Time_O(n)_Space_O(1) #2024_08_24_Time_0_ms_(100.00%)_Space_2.3_MB_(28.72%)

impl Solution {
pub fn length_of_longest_substring(s: String) -> i32 {
// Array to store last seen indices of characters
let mut last_indices = [-1; 256];
let mut max_len = 0;
let mut cur_len = 0;
let mut start = 0;

// Convert string to bytes to use indexing
let bytes = s.as_bytes();
for (i, &cur) in bytes.iter().enumerate() {
// Cast byte to usize to use as an index
let cur = cur as usize;

if last_indices[cur] < start as i32 {
last_indices[cur] = i as i32;
cur_len += 1;
} else {
let last_index = last_indices[cur];
start = (last_index + 1) as usize;
cur_len = i - start + 1;
last_indices[cur] = i as i32;
}

if cur_len > max_len {
max_len = cur_len;
}
}

max_len as i32
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
3\. Longest Substring Without Repeating Characters

Medium

Given a string `s`, find the length of the **longest substring** without repeating characters.

**Example 1:**

**Input:** s = "abcabcbb"

**Output:** 3

**Explanation:** The answer is "abc", with the length of 3.

**Example 2:**

**Input:** s = "bbbbb"

**Output:** 1

**Explanation:** The answer is "b", with the length of 1.

**Example 3:**

**Input:** s = "pwwkew"

**Output:** 3

**Explanation:** The answer is "wke", with the length of 3. Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.

**Example 4:**

**Input:** s = ""

**Output:** 0

**Constraints:**

* <code>0 <= s.length <= 5 * 10<sup>4</sup></code>
* `s` consists of English letters, digits, symbols and spaces.
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
// #Hard #Top_100_Liked_Questions #Top_Interview_Questions #Array #Binary_Search #Divide_and_Conquer
// #Big_O_Time_O(log(min(N,M)))_Space_O(1) #2024_08_24_Time_0_ms_(100.00%)_Space_2.2_MB_(39.80%)

impl Solution {
pub fn find_median_sorted_arrays(nums1: Vec<i32>, nums2: Vec<i32>) -> f64 {
let (nums1, nums2) = if nums1.len() > nums2.len() {
// Ensures nums1 is the smaller array
(nums2, nums1)
} else {
(nums1, nums2)
};

let n1 = nums1.len();
let n2 = nums2.len();
let mut low = 0;
let mut high = n1;

while low <= high {
let cut1 = (low + high) / 2;
let cut2 = (n1 + n2 + 1) / 2 - cut1;

let l1 = if cut1 == 0 { i32::MIN } else { nums1[cut1 - 1] };
let l2 = if cut2 == 0 { i32::MIN } else { nums2[cut2 - 1] };
let r1 = if cut1 == n1 { i32::MAX } else { nums1[cut1] };
let r2 = if cut2 == n2 { i32::MAX } else { nums2[cut2] };

if l1 <= r2 && l2 <= r1 {
// Found the correct partition
if (n1 + n2) % 2 == 0 {
return (f64::from(l1.max(l2)) + f64::from(r1.min(r2))) / 2.0;
} else {
return f64::from(l1.max(l2));
}
} else if l1 > r2 {
high = cut1 - 1;
} else {
low = cut1 + 1;
}
}

// Fallback case, should never hit
0.0
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
4\. Median of Two Sorted Arrays

Hard

Given two sorted arrays `nums1` and `nums2` of size `m` and `n` respectively, return **the median** of the two sorted arrays.

The overall run time complexity should be `O(log (m+n))`.

**Example 1:**

**Input:** nums1 = [1,3], nums2 = [2]

**Output:** 2.00000

**Explanation:** merged array = [1,2,3] and median is 2.

**Example 2:**

**Input:** nums1 = [1,2], nums2 = [3,4]

**Output:** 2.50000

**Explanation:** merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5.

**Example 3:**

**Input:** nums1 = [0,0], nums2 = [0,0]

**Output:** 0.00000

**Example 4:**

**Input:** nums1 = [], nums2 = [1]

**Output:** 1.00000

**Example 5:**

**Input:** nums1 = [2], nums2 = []

**Output:** 2.00000

**Constraints:**

* `nums1.length == m`
* `nums2.length == n`
* `0 <= m <= 1000`
* `0 <= n <= 1000`
* `1 <= m + n <= 2000`
* <code>-10<sup>6</sup> <= nums1[i], nums2[i] <= 10<sup>6</sup></code>
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
// #Medium #Top_100_Liked_Questions #Top_Interview_Questions #String #Dynamic_Programming
// #Data_Structure_II_Day_9_String #Algorithm_II_Day_14_Dynamic_Programming
// #Dynamic_Programming_I_Day_17 #Udemy_Strings #Big_O_Time_O(n)_Space_O(n)
// #2024_08_24_Time_1_ms_(92.60%)_Space_2.2_MB_(20.49%)

impl Solution {
pub fn longest_palindrome(s: String) -> String {
let n = s.len();
if n == 0 {
return String::new();
}

// Step 1: Transform the string to avoid even/odd length issues
let mut new_str = Vec::with_capacity(n * 2 + 1);
new_str.push('#');
for c in s.chars() {
new_str.push(c);
new_str.push('#');
}

let m = new_str.len();
let mut dp = vec![0; m];
let mut friend_center = 0;
let mut friend_radius = 0;
let mut lps_center = 0;
let mut lps_radius = 0;

// Step 2: Apply Manacher's Algorithm
for i in 0..m {
dp[i] = if friend_center + friend_radius > i {
dp[2 * friend_center - i].min(friend_center + friend_radius - i)
} else {
1
};

while i + dp[i] < m && i >= dp[i] && new_str[i + dp[i]] == new_str[i - dp[i]] {
dp[i] += 1;
}

if friend_center + friend_radius < i + dp[i] {
friend_center = i;
friend_radius = dp[i];
}

if lps_radius < dp[i] {
lps_center = i;
lps_radius = dp[i];
}
}

// Step 3: Extract the longest palindromic substring
let start = (lps_center - lps_radius + 1) / 2;
let end = (lps_center + lps_radius - 1) / 2;
s[start..end].to_string()
}
}
Loading

0 comments on commit 686ed81

Please sign in to comment.