From df84d4f18ef3a0e407072e9cf6fc7cb5648d3630 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=A5kon=20St=C3=B8rdal?= <30749741+hakon55@users.noreply.github.com> Date: Sat, 22 Mar 2025 13:49:25 +0100 Subject: [PATCH] =?UTF-8?q?oppgaver=20s=C3=A5=20langt?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- add-binary-67/Cargo.toml | 6 + add-binary-67/src/main.rs | 66 +++++++ binary-tree-inorder-traversal-94/Cargo.toml | 6 + binary-tree-inorder-traversal-94/src/main.rs | 75 ++++++++ climbing-stairs-70/Cargo.toml | 6 + climbing-stairs-70/src/main.rs | 37 ++++ merge-sorted-array-88/Cargo.toml | 6 + merge-sorted-array-88/src/main.rs | 83 ++++++++ plus-one-66/Cargo.toml | 6 + plus-one-66/src/main.rs | 21 ++ .../Cargo.toml | 6 + .../src/main.rs | 51 +++++ remove_duplicates/Cargo.toml | 6 + same-tree-100/Cargo.toml | 6 + same-tree-100/src/main.rs | 181 ++++++++++++++++++ sqrtx-69/Cargo.toml | 6 + sqrtx-69/src/main.rs | 60 ++++++ 17 files changed, 628 insertions(+) create mode 100644 add-binary-67/Cargo.toml create mode 100644 add-binary-67/src/main.rs create mode 100644 binary-tree-inorder-traversal-94/Cargo.toml create mode 100644 binary-tree-inorder-traversal-94/src/main.rs create mode 100644 climbing-stairs-70/Cargo.toml create mode 100644 climbing-stairs-70/src/main.rs create mode 100644 merge-sorted-array-88/Cargo.toml create mode 100644 merge-sorted-array-88/src/main.rs create mode 100644 plus-one-66/Cargo.toml create mode 100644 plus-one-66/src/main.rs create mode 100644 remove-duplicates-from-sorted-list-83/Cargo.toml create mode 100644 remove-duplicates-from-sorted-list-83/src/main.rs create mode 100644 remove_duplicates/Cargo.toml create mode 100644 same-tree-100/Cargo.toml create mode 100644 same-tree-100/src/main.rs create mode 100644 sqrtx-69/Cargo.toml create mode 100644 sqrtx-69/src/main.rs diff --git a/add-binary-67/Cargo.toml b/add-binary-67/Cargo.toml new file mode 100644 index 0000000..3e1683c --- /dev/null +++ b/add-binary-67/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "add-binary-67" +version = "0.1.0" +edition = "2024" + +[dependencies] diff --git a/add-binary-67/src/main.rs b/add-binary-67/src/main.rs new file mode 100644 index 0000000..b10be2b --- /dev/null +++ b/add-binary-67/src/main.rs @@ -0,0 +1,66 @@ +struct Solution {} + +impl Solution { + pub fn add_binary(a: String, b: String) -> String { + let mut result = String::new(); + let mut carry = 0; + + // Convert strings to character vectors and reverse them for easier processing + let a_chars: Vec = a.chars().rev().collect(); + let b_chars: Vec = b.chars().rev().collect(); + + // Get the maximum length of the two strings + let max_len = std::cmp::max(a_chars.len(), b_chars.len()); + + // Perform binary addition digit by digit + for i in 0..max_len { + // Get digits at current position or 0 if we've reached the end + let a_digit = if i < a_chars.len() { + a_chars[i].to_digit(2).unwrap() + } else { + 0 + }; + let b_digit = if i < b_chars.len() { + b_chars[i].to_digit(2).unwrap() + } else { + 0 + }; + + // Calculate sum and new carry + let sum = a_digit + b_digit + carry; + carry = sum / 2; + let digit = sum % 2; + + // Add the current digit to the result + result.push(char::from_digit(digit, 2).unwrap()); + } + + // Don't forget the final carry if it exists + if carry > 0 { + result.push('1'); + } + + // Reverse the result and return + result.chars().rev().collect() + } + + // pub fn add_binary(a: String, b: String) -> String { + // let num1 = u128::from_str_radix(a.as_str(), 2).expect("Valid binary string"); + // let num2 = u128::from_str_radix(b.as_str(), 2).expect("Valid binary string"); + + // let sum = num1 + num2; + + // let binary_sum = format!("{:b}", sum); // format as binary string + + // println!("Sum in decimal: {}", sum); + // println!("Sum in binary: {}", binary_sum); + // binary_sum + // } +} + +fn main() { + let a: String = "111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111".to_string(); + let b: String = "11010100101110111000111".to_string(); + + println!("{:?}", Solution::add_binary(a, b)); +} diff --git a/binary-tree-inorder-traversal-94/Cargo.toml b/binary-tree-inorder-traversal-94/Cargo.toml new file mode 100644 index 0000000..154c0ec --- /dev/null +++ b/binary-tree-inorder-traversal-94/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "binary-tree-inorder-traversal-94" +version = "0.1.0" +edition = "2024" + +[dependencies] diff --git a/binary-tree-inorder-traversal-94/src/main.rs b/binary-tree-inorder-traversal-94/src/main.rs new file mode 100644 index 0000000..93d9d8b --- /dev/null +++ b/binary-tree-inorder-traversal-94/src/main.rs @@ -0,0 +1,75 @@ +// Definition for a binary tree node. +#[derive(Debug, PartialEq, Eq)] +pub struct TreeNode { + pub val: i32, + pub left: Option>>, + pub right: Option>>, +} + +impl TreeNode { + #[inline] + pub fn new(val: i32) -> Self { + TreeNode { + val, + left: None, + right: None, + } + } +} + +use std::cell::RefCell; +use std::rc::Rc; +pub fn inorder_traversal_recursively(root: Option>>) -> Vec { + let mut result = Vec::new(); + helper(&root, &mut result); + result +} + +fn helper(node: &Option>>, result: &mut Vec) { + if let Some(n) = node { + let n = n.borrow(); + helper(&n.left, result); // Left subtree + result.push(n.val); // Current node + helper(&n.right, result); // Right subtree + } +} + +pub fn inorder_traversal(root: Option>>) -> Vec { + let mut result = Vec::new(); + let mut stack = Vec::new(); + let mut current = root; + + while current.is_some() || !stack.is_empty() { + while let Some(node) = current { + stack.push(node.clone()); + current = node.borrow().left.clone(); + } + + if let Some(node) = stack.pop() { + let node = node.borrow(); + result.push(node.val); // Visit current node + current = node.right.clone(); + } + } + + result +} + +fn main() { + let values = vec![ + Some(1), + Some(2), + Some(3), + Some(4), + Some(5), + None, + Some(8), + None, + None, + Some(6), + Some(7), + Some(9), + ]; + + println!("{:?}", values); +} diff --git a/climbing-stairs-70/Cargo.toml b/climbing-stairs-70/Cargo.toml new file mode 100644 index 0000000..6e8ef38 --- /dev/null +++ b/climbing-stairs-70/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "climbing-stairs-70" +version = "0.1.0" +edition = "2024" + +[dependencies] diff --git a/climbing-stairs-70/src/main.rs b/climbing-stairs-70/src/main.rs new file mode 100644 index 0000000..51757c0 --- /dev/null +++ b/climbing-stairs-70/src/main.rs @@ -0,0 +1,37 @@ +fn climb_stairs_on2(n: i32) -> i32 { + if n == 1 { + return 1; + } + + if n == 2 { + return 2; + } + + let sol = climb_stairs(n - 2) + climb_stairs(n - 1); + + sol +} + +fn climb_stairs(n: i32) -> i32 { + if n == 1 { + return 1; + } + if n == 2 { + return 2; + } + + let mut prev = 1; + let mut curr = 2; + + for _ in 3..=n { + let next = prev + curr; + prev = curr; + curr = next; + } + + curr +} + +fn main() { + println!("{}", climb_stairs(4)); +} diff --git a/merge-sorted-array-88/Cargo.toml b/merge-sorted-array-88/Cargo.toml new file mode 100644 index 0000000..400c74a --- /dev/null +++ b/merge-sorted-array-88/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "merge-sorted-array-88" +version = "0.1.0" +edition = "2024" + +[dependencies] diff --git a/merge-sorted-array-88/src/main.rs b/merge-sorted-array-88/src/main.rs new file mode 100644 index 0000000..60d5d71 --- /dev/null +++ b/merge-sorted-array-88/src/main.rs @@ -0,0 +1,83 @@ +pub fn merge_hacky(nums1: &mut Vec, m: i32, nums2: &mut Vec, n: i32) { + if n == 0 { + return; + } + + if m == 0 { + *nums1 = nums2.clone(); + return; + } + + let mut num1_counter = (m - 1) as usize; + let mut num2_counter = (n - 1) as usize; + let while_bool = true; + + // Iterate nums1 from len - n (which is 3) backwards + while while_bool { + let num1 = nums1[num1_counter]; + let num2 = nums2[num2_counter]; + + if num1 < num2 { + nums1[num1_counter + num2_counter + 1] = num2; + if num2_counter == 0 { + break; + } + num2_counter -= 1; + } else if num1 > num2 { + nums1[num1_counter + num2_counter + 1] = num1; + if num1_counter == 0 { + nums1[..num2_counter + 1].copy_from_slice(&nums2[..num2_counter + 1]); + break; + } + num1_counter -= 1 + } else { + nums1[num1_counter + num2_counter] = num2; + nums1[num1_counter + num2_counter + 1] = num1; + if num2_counter == 0 { + break; + } + num2_counter -= 1; + if num1_counter == 0 { + nums1[..num2_counter + 1].copy_from_slice(&nums2[..num2_counter + 1]); + break; + } + num1_counter -= 1 + } + } +} + +pub fn merge(nums1: &mut Vec, m: i32, nums2: &mut Vec, n: i32) { + let mut i = (m - 1) as usize; + let mut j = (n - 1) as usize; + let mut k = (m + n - 1) as usize; + + while let Some(_) = nums1.get(k) { + if j == usize::MAX { + return; + } + + if i == usize::MAX { + nums1[..=j].copy_from_slice(&nums2[..=j]); + return; + } + + if nums1[i] < nums2[j] { + nums1[k] = nums2[j]; + j = j.wrapping_sub(1); + } else { + nums1[k] = nums1[i]; + i = i.wrapping_sub(1); + } + + k = k.wrapping_sub(1); + } +} + +fn main() { + let mut nums1 = vec![2, 0]; + let m = 1; + let mut nums2 = vec![1]; + let n = 1; + println!("{:?}", merge(&mut nums1, m, &mut nums2, n)); + println!("{:?}", nums1) +} diff --git a/plus-one-66/Cargo.toml b/plus-one-66/Cargo.toml new file mode 100644 index 0000000..8615312 --- /dev/null +++ b/plus-one-66/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "plus-one-66" +version = "0.1.0" +edition = "2024" + +[dependencies] diff --git a/plus-one-66/src/main.rs b/plus-one-66/src/main.rs new file mode 100644 index 0000000..3a825da --- /dev/null +++ b/plus-one-66/src/main.rs @@ -0,0 +1,21 @@ +struct Solution {} + +impl Solution { + pub fn plus_one(mut digits: Vec) -> Vec { + for val in digits.iter_mut().rev() { + if *val == 9 { + *val = 0; + } else { + *val += 1; + return digits; + } + } + digits.insert(0, 1); + digits + } +} + +fn main() { + let digits = vec![9, 9, 8]; + println!("{:#?}", Solution::plus_one(digits)); +} diff --git a/remove-duplicates-from-sorted-list-83/Cargo.toml b/remove-duplicates-from-sorted-list-83/Cargo.toml new file mode 100644 index 0000000..3f370bd --- /dev/null +++ b/remove-duplicates-from-sorted-list-83/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "remove-duplicates-from-sorted-list-83" +version = "0.1.0" +edition = "2024" + +[dependencies] diff --git a/remove-duplicates-from-sorted-list-83/src/main.rs b/remove-duplicates-from-sorted-list-83/src/main.rs new file mode 100644 index 0000000..f30968c --- /dev/null +++ b/remove-duplicates-from-sorted-list-83/src/main.rs @@ -0,0 +1,51 @@ +// Definition for singly-linked list. +#[derive(PartialEq, Eq, Clone, Debug)] +pub struct ListNode { + pub val: i32, + pub next: Option>, +} + +impl ListNode { + #[inline] + fn new(val: i32) -> Self { + ListNode { next: None, val } + } +} + +pub fn to_linked_list(values: &[i32]) -> Option> { + let mut head = None; + let mut current = &mut head; + + for &val in values { + *current = Some(Box::new(ListNode::new(val))); + current = &mut current.as_mut().unwrap().next; + } + + head +} + +pub fn delete_duplicates(mut head: Option>) -> Option> { + let mut current = head.as_mut(); + + while let Some(node) = current { + while let Some(next) = node.next.as_mut() { + // Mutably borrow next + if node.val == next.val { + node.next = next.next.take(); // Take ownership of the next node safely + } else { + break; + } + } + current = node.next.as_mut(); // Move to the next distinct node + } + + head +} + +fn main() { + let values = [1, 2, 3, 3, 4]; + let head = to_linked_list(&values); + println!("{:?}", head); + println!("{:?}", delete_duplicates(head)); + +} diff --git a/remove_duplicates/Cargo.toml b/remove_duplicates/Cargo.toml new file mode 100644 index 0000000..aa2b25b --- /dev/null +++ b/remove_duplicates/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "remove_duplicates" +version = "0.1.0" +edition = "2024" + +[dependencies] diff --git a/same-tree-100/Cargo.toml b/same-tree-100/Cargo.toml new file mode 100644 index 0000000..11b69e7 --- /dev/null +++ b/same-tree-100/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "same-tree-100" +version = "0.1.0" +edition = "2024" + +[dependencies] diff --git a/same-tree-100/src/main.rs b/same-tree-100/src/main.rs new file mode 100644 index 0000000..ecca86b --- /dev/null +++ b/same-tree-100/src/main.rs @@ -0,0 +1,181 @@ +// Definition for a binary tree node. +#[derive(Debug, PartialEq, Eq)] +pub struct TreeNode { + pub val: i32, + pub left: Option>>, + pub right: Option>>, +} + +impl TreeNode { + #[inline] + pub fn new(val: i32) -> Self { + TreeNode { + val, + left: None, + right: None, + } + } +} +struct Solution {} + +use std::cell::RefCell; +use std::rc::Rc; +impl Solution { + pub fn is_same_tree( + p: Option>>, + q: Option>>, + ) -> bool { + // Base cases: if either is None + match (p, q) { + // Both are None - trees are identical (empty) + (None, None) => true, + + // One is None but the other isn't - trees are different + (Some(_), None) | (None, Some(_)) => false, + + // Both trees have nodes - compare them recursively + (Some(p_node), Some(q_node)) => { + let p_borrow = p_node.borrow(); + let q_borrow = q_node.borrow(); + + // Trees are the same if: + // 1. Current nodes have the same value + // 2. Left subtrees are the same + // 3. Right subtrees are the same + p_borrow.val == q_borrow.val + && Solution::is_same_tree(p_borrow.left.clone(), q_borrow.left.clone()) + && Solution::is_same_tree(p_borrow.right.clone(), q_borrow.right.clone()) + } + } + } +} + +pub fn is_same_tree_iterativly(p: Option>>, q: Option>>) -> bool { + // Create a stack to store pairs of nodes to compare + let mut stack = Vec::new(); + + // Push the root pair to the stack + stack.push((p, q)); + + // Process nodes until the stack is empty + while !stack.is_empty() { + if let Some((p_opt, q_opt)) = stack.pop() { + match (p_opt, q_opt) { + // Both nodes are None, continue checking other pairs + (None, None) => continue, + + // One node is None while the other isn't - trees differ + (Some(_), None) | (None, Some(_)) => return false, + + // Both nodes exist, compare them + (Some(p_node), Some(q_node)) => { + let p_borrow = p_node.borrow(); + let q_borrow = q_node.borrow(); + + // If values are different, trees differ + if p_borrow.val != q_borrow.val { + return false; + } + + // Push right children to stack + stack.push(( + p_borrow.right.clone(), + q_borrow.right.clone() + )); + + // Push left children to stack + stack.push(( + p_borrow.left.clone(), + q_borrow.left.clone() + )); + } + } + } + } + + // If we've processed all nodes without finding differences, trees are identical + true +} + +// Helper function to create trees from arrays +fn create_tree_from_vec(nums: &[Option], index: usize) -> Option>> { + if index >= nums.len() || nums[index].is_none() { + return None; + } + + let val = nums[index].unwrap(); + let mut node = TreeNode::new(val); + + // Create left child (2*index + 1) + node.left = create_tree_from_vec(nums, 2 * index + 1); + + // Create right child (2*index + 2) + node.right = create_tree_from_vec(nums, 2 * index + 2); + + Some(Rc::new(RefCell::new(node))) +} + +fn main() { + // Test case 1: Two identical trees + // 1 + // / \ + // 2 3 + let tree1_data = vec![Some(1), Some(2), Some(3)]; + let tree1 = create_tree_from_vec(&tree1_data, 0); + let tree2 = create_tree_from_vec(&tree1_data, 0); + + // Expected: true + println!("Test case 1: {}", is_same_tree_iterativly(tree1, tree2)); + + // Test case 2: Different values in nodes + // 1 1 + // / \ / \ + // 2 3 2 4 + let tree3_data = vec![Some(1), Some(2), Some(3)]; + let tree4_data = vec![Some(1), Some(2), Some(4)]; + let tree3 = create_tree_from_vec(&tree3_data, 0); + let tree4 = create_tree_from_vec(&tree4_data, 0); + + // Expected: false + println!("Test case 2: {}", Solution::is_same_tree(tree3, tree4)); + + // Test case 3: Different structure + // 1 1 + // / \ \ + // 2 3 3 + let tree5_data = vec![Some(1), Some(2), Some(3)]; + let tree6_data = vec![Some(1), None, Some(3)]; + let tree5 = create_tree_from_vec(&tree5_data, 0); + let tree6 = create_tree_from_vec(&tree6_data, 0); + + // Expected: false + println!("Test case 3: {}", Solution::is_same_tree(tree5, tree6)); + + // Test case 4: Empty trees + let tree7: Option>> = None; + let tree8: Option>> = None; + + // Expected: true + println!("Test case 4: {}", Solution::is_same_tree(tree7, tree8)); + + // Test case 5: One empty, one not + let tree9_data = vec![Some(1)]; + let tree9 = create_tree_from_vec(&tree9_data, 0); + let tree10: Option>> = None; + + // Expected: false + println!("Test case 5: {}", Solution::is_same_tree(tree9, tree10)); + + // Test case 6: More complex identical trees + // 1 + // / \ + // 2 3 + // / \ + // 4 5 + let tree11_data = vec![Some(1), Some(2), Some(3), Some(4), None, None, Some(5)]; + let tree11 = create_tree_from_vec(&tree11_data, 0); + let tree12 = create_tree_from_vec(&tree11_data, 0); + + // Expected: true + println!("Test case 6: {}", Solution::is_same_tree(tree11, tree12)); +} \ No newline at end of file diff --git a/sqrtx-69/Cargo.toml b/sqrtx-69/Cargo.toml new file mode 100644 index 0000000..2fe621c --- /dev/null +++ b/sqrtx-69/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "sqrtx-69" +version = "0.1.0" +edition = "2024" + +[dependencies] diff --git a/sqrtx-69/src/main.rs b/sqrtx-69/src/main.rs new file mode 100644 index 0000000..aef63f0 --- /dev/null +++ b/sqrtx-69/src/main.rs @@ -0,0 +1,60 @@ +// fn my_sqrt(x: i32) -> i32 { +// let mut upper_range = x / 2; +// let mut last_i = 0; + +// if x <= 5 { +// upper_range = x; +// } + +// if x >= i32::MAX { +// return (i32::MAX as f64).sqrt().floor() as i32; +// } + +// for i in 0..=upper_range { +// let power_of_2 = i * i; + +// if power_of_2 == x { +// return i; +// } else if power_of_2 > x { +// return last_i; +// } else { +// last_i = i; +// } +// } +// 0 +// } + +fn my_sqrt(x: i32) -> i32 { + if x < 2 { + return x; // Early return for 0 and 1 + } + + let mut right = 46340.min(x / 2); + + if x >= right * right { + return right; + } + + let mut left = 2; + + while left <= right { + let mid = left + (right - left) / 2; + let mid_squared = mid * mid; + + if mid_squared == x { + return mid; + } else if mid_squared < x { + left = mid + 1; + } else { + right = mid - 1; + } + } + + right // After the loop, `right` is the largest value whose square is <= x} +} + +fn main() { + // let sol = my_sqrt(2147483647); + let sol = my_sqrt(2147395599); + println!("{}", sol); +}