├── .gitignore
├── .idea
├── .gitignore
├── leetcode-solutions.iml
├── modules.xml
└── vcs.xml
├── .vscode
└── settings.json
├── 100-Same-Tree
├── desc.txt
├── py
│ └── main.py
├── rs
│ ├── Cargo.toml
│ ├── go
│ │ └── main.go
│ └── src
│ │ └── main.rs
└── ts
│ └── main.ts
├── 141-Linked-List-Cycle
├── desc.txt
├── go
│ └── main.go
├── py
│ └── main.py
└── ts
│ └── main.ts
├── 1609-Even-Odd-Tree
├── desc.txt
├── go
│ └── main.go
├── py
│ └── main.py
├── rs
│ ├── Cargo.toml
│ └── src
│ │ └── main.rs
└── ts
│ └── main.ts
├── 1750-Minimum-Length-of-String-After-Deleting-Similar-Ends
├── desc.txt
├── go
│ └── main.go
├── py
│ └── main.py
├── rs
│ ├── Cargo.toml
│ └── src
│ │ └── main.rs
└── ts
│ └── main.ts
├── 234-Palindrome-Linked-List
├── desc.txt
├── go
│ └── main.go
├── py
│ └── main.py
├── rs
│ ├── Cargo.toml
│ └── src
│ │ └── main.rs
└── ts
│ └── main.ts
├── 2698-Find-the-Punishment-Number-of-an-Integer
├── desc.txt
├── go
│ └── main.go
├── rs
│ └── main.rs
└── ts
│ └── main.ts
├── 2864-Maximum-Odd-Binary-Number
├── desc.txt
├── go
│ └── main.go
├── py
│ └── main.py
├── rs
│ ├── Cargo.toml
│ └── src
│ │ └── main.rs
└── ts
│ ├── main.js
│ └── main.ts
├── 287-Find-the-Duplicate-Number
├── go
│ └── main.go
├── py
│ └── main.py
├── rs
│ └── main.rs
└── ts
│ └── main.ts
├── 3005-Count-Elements-With-Maximum-Frequency
├── desc.txt
├── go
│ └── main.go
├── rs
│ ├── Cargo.toml
│ └── src
│ │ └── main.rs
└── ts
│ └── main.ts
├── 349-Intersection-of-Two-Arrays
├── desc.txt
├── go
│ └── main.go
├── py
│ └── main.py
├── rs
│ ├── Cargo.toml
│ └── src
│ │ └── main.rs
└── ts
│ └── main.ts
├── 402-Remove-K-Digits
├── c
│ └── main.c
├── desc.txt
├── go
│ └── main.go
├── py
│ └── main.py
├── rs
│ └── main.rs
└── ts
│ └── main.ts
├── 41-First-Missing-Positive
├── desc.txt
├── go
│ └── main.go
├── py
│ └── main.py
├── rs
│ └── main.rs
└── ts
│ └── main.ts
├── 442-Find-All-Duplicates-in-an-Array
├── desc.txt
├── go
│ └── main.go
├── py
│ └── main.py
├── rs
│ └── main.rs
└── ts
│ └── main.ts
├── 452-Minimum-Number-of-Arrows-to-Burst-Balloons
├── desc.txt
├── go
│ └── main.go
├── py
│ └── main.py
├── rs
│ ├── Cargo.toml
│ └── src
│ │ └── main.rs
└── ts
│ └── main.ts
├── 543-Diameter-of-Binary-Tree
├── desc.text
├── go
│ └── main.go
├── py
│ └── main.py
├── rs
│ ├── Cargo.lock
│ ├── Cargo.toml
│ └── src
│ │ └── main.rs
└── ts
│ └── main.ts
├── 876-Middle-of-the-Linked-List
├── desc.txt
├── go
│ └── main.go
├── py
│ └── main.py
├── rs
│ ├── Cargo.toml
│ └── src
│ │ └── main.rs
└── ts
│ └── main.ts
├── 948-Bag-of-Token
├── desc.txt
├── go
│ └── main.go
├── py
│ └── main.py
├── rs
│ ├── Cargo.toml
│ └── src
│ │ └── main.rs
└── ts
│ └── main.ts
├── Cheapest-Flights-Within-K-Stops
├── desc.txt
├── py
│ └── main.py
└── rust
│ ├── Cargo.lock
│ ├── Cargo.toml
│ └── src
│ └── main.rs
├── Find-the-Town-Judge
├── desc.txt
├── go
│ └── main.go
├── rust
│ ├── Cargo.toml
│ └── src
│ │ └── main.rs
└── ts
│ └── main.ts
├── README.md
├── bitwise-AND-of-number-range
├── Rust
│ ├── Cargo.toml
│ └── src
│ │ └── main.rs
├── desc.txt
├── go
│ └── main.go
├── py
│ └── main.py
└── ts
│ └── main.ts
├── cherry-pickup-II-py
├── desc.txt
└── main.py
├── find-first-palindromic-string-in-array
├── Cargo.toml
├── desc.txt
└── src
│ └── main.rs
├── find-polygon-with-largest-perimeter
├── Cargo.toml
├── desc.txt
└── src
│ └── main.rs
├── furtherest-building-you-can-reach
├── Cargo.lock
├── Cargo.toml
├── desc.txt
└── src
│ └── main.rs
├── group-anagrams
├── Cargo.lock
├── Cargo.toml
├── desc.txt
└── src
│ └── main.rs
├── least-number-of-integers-after-k-removals
├── Cargo.toml
├── desc.txt
└── src
│ └── main.rs
├── longest-common-prefix
├── Cargo.lock
├── Cargo.toml
├── desc.txt
└── src
│ └── main.rs
├── majority-element
├── Cargo.toml
├── desc.txt
└── src
│ └── main.rs
├── meeting-rooms-III
├── desc.txt
├── meeting-room-III-rs
│ ├── Cargo.toml
│ └── src
│ │ └── main.rs
└── py-solution
│ └── main.py
├── missing-number
├── Cargo.toml
├── desc.txt
└── src
│ └── main.rs
├── palindrome-number
├── Cargo.toml
├── desc.txt
└── src
│ └── main.rs
├── perfect-squares-idk
├── Cargo.lock
├── Cargo.toml
├── desc.txt
└── src
│ └── main.rs
├── power-of-two
├── Cargo.toml
├── desc.txt
└── src
│ └── main.rs
├── rearrange-array-element-by-sign
├── Cargo.toml
├── desc.txt
└── src
│ └── main.rs
├── remove-duplicate-from-sorted-arrays
├── Cargo.toml
├── desc.txt
└── src
│ └── main.rs
├── roman-to-integer
├── Cargo.lock
├── Cargo.toml
├── desc.txt
└── src
│ └── main.rs
├── sort-characters-by-frequency
├── Cargo.lock
├── Cargo.toml
└── src
│ ├── desc.txt
│ └── main.rs
├── two-sum
├── Cargo.lock
├── Cargo.toml
└── src
│ └── main.rs
└── valid-parenthesis
├── Cargo.lock
├── Cargo.toml
├── desc.txt
└── src
└── main.rs
/.gitignore:
--------------------------------------------------------------------------------
1 | ./1750-Minimum-Length-of-String-After-Deleting-Similar-Ends/rs/target
2 | ./100-Same-Tree/rs/target
3 | ./543-Diameter-of-Binary-Tree/rs/target
4 | ./948-Bag-of-Token/rs/target
5 | ./1609-Even-Odd-Tree/rs/target
6 | ./2864-Maximum-Odd-Binary-Number/rs/target
7 | ./bitwise-AND-of-number-range/Rust/target
8 | ./Cheapest-Flights-Within-K-Stops/rust/target
9 | ./find-first-palindromic-string-in-array/target
10 | ./find-polygon-with-largest-perimeter/target
11 | ./Find-the-Town-Judge/rust/target
12 | ./furtherest-building-you-can-reach/target
13 | ./group-anagrams/target
14 | ./least-number-of-integers-after-k-removals/target
15 | ./longest-common-prefix/target
16 | ./majority-element/target
17 | ./meeting-rooms-III\meeting-room-III-rs/target
18 | ./missing-number/target
19 | ./palindrome-number/target
20 | ./perfect-squares-idk/target
21 | ./power-of-two/target
22 | ./rearrange-array-element-by-sign/target
23 | ./remove-duplicate-from-sorted-arrays/target
24 | ./roman-to-integer/target
25 | ./sort-characters-by-frequency/target
26 | ./two-sum/target
27 | ./valid-parenthesis/target
28 | ./876-Middle-of-the-Linked-List/rs/target
--------------------------------------------------------------------------------
/.idea/.gitignore:
--------------------------------------------------------------------------------
1 | # Default ignored files
2 | /shelf/
3 | /workspace.xml
4 | # Editor-based HTTP Client requests
5 | /httpRequests/
6 | # Datasource local storage ignored files
7 | /dataSources/
8 | /dataSources.local.xml
9 |
--------------------------------------------------------------------------------
/.idea/leetcode-solutions.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.vscode/settings.json:
--------------------------------------------------------------------------------
1 | {
2 | "rust-analyzer.linkedProjects": [
3 | "./perfect-squares-idk/Cargo.toml"
4 | ]
5 | }
--------------------------------------------------------------------------------
/100-Same-Tree/desc.txt:
--------------------------------------------------------------------------------
1 | Given the roots of two binary trees p and q, write a function to check if they are the same or not.
2 |
3 | Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.
4 |
5 |
6 |
7 | Example 1:
8 |
9 | Input: p = [1,2,3], q = [1,2,3]
10 | Output: true
11 |
12 | Example 2:
13 |
14 | Input: p = [1,2], q = [1,null,2]
15 | Output: false
16 |
17 | Example 3:
18 |
19 | Input: p = [1,2,1], q = [1,1,2]
20 | Output: false
21 |
22 |
23 |
24 | Constraints:
25 |
26 | The number of nodes in both trees is in the range [0, 100].
27 | -104 <= Node.val <= 104
28 |
29 |
--------------------------------------------------------------------------------
/100-Same-Tree/py/main.py:
--------------------------------------------------------------------------------
1 | # Definition for a binary tree node.
2 | # class TreeNode:
3 | # def __init__(self, val=0, left=None, right=None):
4 | # self.val = val
5 | # self.left = left
6 | # self.right = right
7 | class Solution:
8 | def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
9 | if p is None or q is None :
10 | return p==q
11 | if p.val != q.val:
12 | return False
13 | return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
14 |
--------------------------------------------------------------------------------
/100-Same-Tree/rs/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "rs"
3 | version = "0.1.0"
4 | edition = "2021"
5 |
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 |
8 | [dependencies]
9 |
--------------------------------------------------------------------------------
/100-Same-Tree/rs/go/main.go:
--------------------------------------------------------------------------------
1 | /**
2 | * Definition for a binary tree node.
3 | * type TreeNode struct {
4 | * Val int
5 | * Left *TreeNode
6 | * Right *TreeNode
7 | * }
8 | */
9 | func isSameTree(p *TreeNode, q *TreeNode) bool {
10 | if(p==nil || q == nil) {
11 | return p == q
12 | }
13 | if p.Val != q.Val {
14 | return false
15 | }
16 | return isSameTree(p.Left, q.Left) && isSameTree(p.Right, q.Right)
17 | }
--------------------------------------------------------------------------------
/100-Same-Tree/rs/src/main.rs:
--------------------------------------------------------------------------------
1 | // Definition for a binary tree node.
2 | // #[derive(Debug, PartialEq, Eq)]
3 | // pub struct TreeNode {
4 | // pub val: i32,
5 | // pub left: Option>>,
6 | // pub right: Option>>,
7 | // }
8 | //
9 | // impl TreeNode {
10 | // #[inline]
11 | // pub fn new(val: i32) -> Self {
12 | // TreeNode {
13 | // val,
14 | // left: None,
15 | // right: None
16 | // }
17 | // }
18 | // }
19 | use std::rc::Rc;
20 | use std::cell::RefCell;
21 | impl Solution {
22 | pub fn is_same_tree(p: Option>>, q: Option>>) -> bool {
23 | p==q
24 | }
25 | }
--------------------------------------------------------------------------------
/100-Same-Tree/ts/main.ts:
--------------------------------------------------------------------------------
1 |
2 | // Definition for a binary tree node.
3 | class TreeNode {
4 | val: number
5 | left: TreeNode | null
6 | right: TreeNode | null
7 | constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
8 | this.val = (val===undefined ? 0 : val)
9 | this.left = (left===undefined ? null : left)
10 | this.right = (right===undefined ? null : right)
11 | }
12 | }
13 |
14 |
15 | function isSameTree(p: TreeNode | null, q: TreeNode | null): boolean {
16 | if(p == null || q == null) {
17 | return p ==q
18 | }
19 | if (p.val != q.val) {
20 | return false
21 | }
22 | return isSameTree(p.left, q.left) && isSameTree(p.right, q.right)
23 | };
--------------------------------------------------------------------------------
/141-Linked-List-Cycle/desc.txt:
--------------------------------------------------------------------------------
1 | Given head, the head of a linked list, determine if the linked list has a cycle in it.
2 |
3 | There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to. Note that pos is not passed as a parameter.
4 |
5 | Return true if there is a cycle in the linked list. Otherwise, return false.
6 |
7 |
8 |
9 | Example 1:
10 |
11 | Input: head = [3,2,0,-4], pos = 1
12 | Output: true
13 | Explanation: There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).
14 |
15 | Example 2:
16 |
17 | Input: head = [1,2], pos = 0
18 | Output: true
19 | Explanation: There is a cycle in the linked list, where the tail connects to the 0th node.
20 |
21 | Example 3:
22 |
23 | Input: head = [1], pos = -1
24 | Output: false
25 | Explanation: There is no cycle in the linked list.
26 |
27 |
28 |
29 | Constraints:
30 |
31 | The number of the nodes in the list is in the range [0, 104].
32 | -105 <= Node.val <= 105
33 | pos is -1 or a valid index in the linked-list.
34 |
--------------------------------------------------------------------------------
/141-Linked-List-Cycle/go/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import(
4 | "fmt"
5 | )
6 |
7 | type ListNode struct {
8 | Val int
9 | Next *ListNode
10 | }
11 |
12 | func hasCycle(head *ListNode) bool {
13 | if head == nil || head.Next == nil {
14 | return false
15 | }
16 |
17 | seen := make(map[*ListNode]bool)
18 | cur := head
19 |
20 | for cur != nil {
21 | if _, exists := seen[cur]; exists {
22 | return true
23 | }
24 |
25 | seen[cur] = true
26 | cur = cur.Next
27 | }
28 |
29 | return false
30 | }
31 |
32 | func createLinkedList(values []int, pos int) *ListNode {
33 | var head, curr *ListNode
34 | nodes := make([]*ListNode, len(values))
35 |
36 | for i, val := range values {
37 | node := &ListNode{Val: val}
38 | nodes[i] = node
39 |
40 | if i == 0 {
41 | head = node
42 | } else {
43 | curr.Next = node
44 | }
45 |
46 | curr = node
47 | }
48 |
49 | // Create a cycle if pos is valid
50 | if pos >= 0 && pos < len(values) {
51 | curr.Next = nodes[pos]
52 | }
53 |
54 | return head
55 | }
56 |
57 | func main() {
58 | values := []int{3, 2, 0, -4}
59 | pos := 1
60 |
61 | head := createLinkedList(values, pos)
62 | hasCycle(head)
63 | }
64 |
--------------------------------------------------------------------------------
/141-Linked-List-Cycle/py/main.py:
--------------------------------------------------------------------------------
1 | # Definition for singly-linked list.
2 | # class ListNode:
3 | # def __init__(self, x):
4 | # self.val = x
5 | # self.next = None
6 |
7 | class Solution:
8 | def hasCycle(self, head: Optional[ListNode]) -> bool:
9 | if not head or not head.next :
10 | return False
11 |
12 | seen = set()
13 | current = head
14 |
15 | while current :
16 | if current in seen :
17 | return True
18 | seen.add(current)
19 | current = current.next
20 | return False
21 |
--------------------------------------------------------------------------------
/141-Linked-List-Cycle/ts/main.ts:
--------------------------------------------------------------------------------
1 | /**
2 | * Definition for singly-linked list.
3 | * class ListNode {
4 | * val: number
5 | * next: ListNode | null
6 | * constructor(val?: number, next?: ListNode | null) {
7 | * this.val = (val===undefined ? 0 : val)
8 | * this.next = (next===undefined ? null : next)
9 | * }
10 | * }
11 | */
12 |
13 | function hasCycle(head: ListNode | null): boolean {
14 | if (!head || !head.next ) {
15 | return false;
16 | }
17 |
18 | let seen = [];
19 | let current = head
20 |
21 | while (current != null) {
22 | if (seen.includes(current)) {
23 | return true;
24 | }
25 | seen.push(current)
26 | current = current.next
27 | }
28 | return false
29 |
30 | };
31 |
--------------------------------------------------------------------------------
/1609-Even-Odd-Tree/desc.txt:
--------------------------------------------------------------------------------
1 | A binary tree is named Even-Odd if it meets the following conditions:
2 |
3 | The root of the binary tree is at level index 0, its children are at level index 1, their children are at level index 2, etc.
4 | For every even-indexed level, all nodes at the level have odd integer values in strictly increasing order (from left to right).
5 | For every odd-indexed level, all nodes at the level have even integer values in strictly decreasing order (from left to right).
6 |
7 | Given the root of a binary tree, return true if the binary tree is Even-Odd, otherwise return false.
8 |
9 |
10 |
11 | Example 1:
12 |
13 | Input: root = [1,10,4,3,null,7,9,12,8,6,null,null,2]
14 | Output: true
15 | Explanation: The node values on each level are:
16 | Level 0: [1]
17 | Level 1: [10,4]
18 | Level 2: [3,7,9]
19 | Level 3: [12,8,6,2]
20 | Since levels 0 and 2 are all odd and increasing and levels 1 and 3 are all even and decreasing, the tree is Even-Odd.
21 |
22 | Example 2:
23 |
24 | Input: root = [5,4,2,3,3,7]
25 | Output: false
26 | Explanation: The node values on each level are:
27 | Level 0: [5]
28 | Level 1: [4,2]
29 | Level 2: [3,3,7]
30 | Node values in level 2 must be in strictly increasing order, so the tree is not Even-Odd.
31 |
32 | Example 3:
33 |
34 | Input: root = [5,9,1,3,5,7]
35 | Output: false
36 | Explanation: Node values in the level 1 should be even integers.
37 |
38 |
39 |
40 | Constraints:
41 |
42 | The number of nodes in the tree is in the range [1, 105].
43 | 1 <= Node.val <= 106
44 |
45 |
--------------------------------------------------------------------------------
/1609-Even-Odd-Tree/go/main.go:
--------------------------------------------------------------------------------
1 |
2 |
3 | import (
4 | "container/list"
5 | )
6 |
7 | /**
8 | * Definition for a binary tree node.
9 | * type TreeNode struct {
10 | * Val int
11 | * Left *TreeNode
12 | * Right *TreeNode
13 | * }
14 | */
15 | func isEvenOddTree(root *TreeNode) bool {
16 | if root == nil {
17 | return true
18 | }
19 |
20 | queue := list.New()
21 | queue.PushBack(root)
22 |
23 | level := 0
24 | for queue.Len() != 0 {
25 | n := queue.Len()
26 | cur := 0
27 | for i := 0; i < n; i++ {
28 | e := queue.Front()
29 | node := e.Value.(*TreeNode)
30 |
31 | if level%2 == 0 && ((cur != 0 && cur >= node.Val) || node.Val%2 == 0 ) {
32 | return false
33 | }
34 | if level%2 == 1 && ((cur != 0 && cur <= node.Val) || node.Val%2 == 1 ) {
35 | return false
36 | }
37 |
38 | cur = node.Val
39 |
40 | if node.Left != nil {
41 | queue.PushBack(node.Left)
42 | }
43 | if node.Right != nil {
44 | queue.PushBack(node.Right)
45 | }
46 | queue.Remove(e)
47 | }
48 | level++
49 | }
50 | return true
51 | }
52 |
53 |
54 | func main(){}
55 |
--------------------------------------------------------------------------------
/1609-Even-Odd-Tree/py/main.py:
--------------------------------------------------------------------------------
1 | # Definition for a binary tree node.
2 | # class TreeNode:
3 | # def __init__(self, val=0, left=None, right=None):
4 | # self.val = val
5 | # self.left = left
6 | # self.right = right
7 | class Solution:
8 | def isEvenOddTree(self, root: Optional[TreeNode]) -> bool:
9 | even = True
10 | q = deque([root])
11 |
12 | while q:
13 | prev = float("-inf") if even else float("inf")
14 | for _ in range(len(q)):
15 | node = q.popleft()
16 |
17 | if even and (node.val % 2 == 0 or node.val <= prev):
18 | return False
19 | elif not even and (node.val % 2 == 1 or node.val >= prev):
20 | return False
21 | if node.left:
22 | q.append(node.left)
23 | if node.right:
24 | q.append(node.right)
25 |
26 | prev = node.val
27 | even = not even
28 | return True
29 |
--------------------------------------------------------------------------------
/1609-Even-Odd-Tree/rs/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "rs"
3 | version = "0.1.0"
4 | edition = "2021"
5 |
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 |
8 | [dependencies]
9 |
--------------------------------------------------------------------------------
/1609-Even-Odd-Tree/rs/src/main.rs:
--------------------------------------------------------------------------------
1 | fn main() {
2 | println!("Hello, world!");
3 | }
4 |
5 | // Definition for a binary tree node.
6 | #[derive(Debug, PartialEq, Eq)]
7 | pub struct TreeNode {
8 | pub val: i32,
9 | pub left: Option>>,
10 | pub right: Option>>,
11 | }
12 |
13 | impl TreeNode {
14 | #[inline]
15 | pub fn new(val: i32) -> Self {
16 | TreeNode {
17 | val,
18 | left: None,
19 | right: None
20 | }
21 | }
22 | }
23 | use std::rc::Rc;
24 | use std::cell::RefCell;
25 | use std::collections::VecDeque;
26 | impl Solution {
27 | pub fn is_even_odd_tree(root: Option>>) -> bool {
28 | let mut even = true;
29 | let mut q = VecDeque::new();
30 | q.push_back(root.unwrap());
31 |
32 | while ! q.is_empty() {
33 | let mut prev = if even {i32::MIN} else {i32::MAX};
34 | for _ in 0..q.len() {
35 | let node = q.pop_front().unwrap();
36 | let node = node.borrow();
37 |
38 | if even && (node.val % 2 == 0 || node.val <= prev) {
39 | return false;
40 | } else if !even && (node.val % 2 == 1 || node.val >= prev) {
41 | return false;
42 | }
43 |
44 | if let Some(left) = &node.left {
45 | q.push_back(Rc::clone(left));
46 | }
47 | if let Some(right) = &node.right {
48 | q.push_back(Rc::clone(right));
49 | }
50 |
51 | prev = node.val;
52 | }
53 | even = !even;
54 | }
55 | true
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/1609-Even-Odd-Tree/ts/main.ts:
--------------------------------------------------------------------------------
1 | /**
2 | * Definition for a binary tree node.
3 | * class TreeNode {
4 | * val: number
5 | * left: TreeNode | null
6 | * right: TreeNode | null
7 | * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
8 | * this.val = (val===undefined ? 0 : val)
9 | * this.left = (left===undefined ? null : left)
10 | * this.right = (right===undefined ? null : right)
11 | * }
12 | * }
13 | */
14 |
15 | function isEvenOddTree(root: TreeNode | null): boolean {
16 | if (root === null) {
17 | return true;
18 | }
19 |
20 | let queue: Array = [root];
21 | let level = 0;
22 |
23 | while (queue.length !== 0) {
24 | let n = queue.length;
25 | let cur = 0;
26 |
27 | for (let i = 0; i < n; i++) {
28 | let node = queue.shift()!;
29 |
30 | if (level % 2 === 0 && ((cur !== 0 && cur >= node.val) || node.val % 2 === 0)) {
31 | return false;
32 | }
33 | if (level % 2 === 1 && ((cur !== 0 && cur <= node.val) || node.val % 2 === 1)) {
34 | return false;
35 | }
36 |
37 | cur = node.val;
38 |
39 | if (node.left !== null) {
40 | queue.push(node.left);
41 | }
42 | if (node.right !== null) {
43 | queue.push(node.right);
44 | }
45 | }
46 | level++;
47 | }
48 | return true;
49 | }
50 |
--------------------------------------------------------------------------------
/1750-Minimum-Length-of-String-After-Deleting-Similar-Ends/desc.txt:
--------------------------------------------------------------------------------
1 | Given a string s consisting only of characters 'a', 'b', and 'c'. You are asked to apply the following algorithm on the string any number of times:
2 |
3 | Pick a non-empty prefix from the string s where all the characters in the prefix are equal.
4 | Pick a non-empty suffix from the string s where all the characters in this suffix are equal.
5 | The prefix and the suffix should not intersect at any index.
6 | The characters from the prefix and suffix must be the same.
7 | Delete both the prefix and the suffix.
8 |
9 | Return the minimum length of s after performing the above operation any number of times (possibly zero times).
10 |
11 |
12 |
13 | Example 1:
14 |
15 | Input: s = "ca"
16 | Output: 2
17 | Explanation: You can't remove any characters, so the string stays as is.
18 |
19 | Example 2:
20 |
21 | Input: s = "cabaabac"
22 | Output: 0
23 | Explanation: An optimal sequence of operations is:
24 | - Take prefix = "c" and suffix = "c" and remove them, s = "abaaba".
25 | - Take prefix = "a" and suffix = "a" and remove them, s = "baab".
26 | - Take prefix = "b" and suffix = "b" and remove them, s = "aa".
27 | - Take prefix = "a" and suffix = "a" and remove them, s = "".
28 |
29 | Example 3:
30 |
31 | Input: s = "aabccabba"
32 | Output: 3
33 | Explanation: An optimal sequence of operations is:
34 | - Take prefix = "aa" and suffix = "a" and remove them, s = "bccabb".
35 | - Take prefix = "b" and suffix = "bb" and remove them, s = "cca".
36 |
37 |
38 |
39 | Constraints:
40 |
41 | 1 <= s.length <= 105
42 | s only consists of characters 'a', 'b', and 'c'.
43 |
44 |
--------------------------------------------------------------------------------
/1750-Minimum-Length-of-String-After-Deleting-Similar-Ends/go/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | )
6 |
7 | func main() {
8 | fmt.Println("Hello World")
9 | s := "aabccabba"
10 | fmt.Println(minimumLength(s))
11 |
12 | }
13 |
14 | func minimumLength(s string) int {
15 |
16 | left := 0
17 | right := len(s) - 1
18 | // fmt.Println(s[0])
19 |
20 | for left < right {
21 | if s[left] == s[right] {
22 | same := s[left]
23 | for left <= right && s[left] == same {
24 | left += 1
25 | }
26 | for left <= right && s[right] == same {
27 | right -= 1
28 | }
29 | } else {
30 | break
31 | }
32 | }
33 | return right - left + 1
34 | }
35 |
--------------------------------------------------------------------------------
/1750-Minimum-Length-of-String-After-Deleting-Similar-Ends/py/main.py:
--------------------------------------------------------------------------------
1 | def minimumLength(self, s: str) -> int:
2 | left = 0
3 | right = len(s) - 1
4 |
5 | while left < right :
6 | if s[left] == s[right] :
7 | same = s[left]
8 | while (left<=right and s[left] == same) :
9 | left += 1
10 | while left<=right and s[right] == same :
11 | right -= 1
12 | else :
13 | break
14 |
15 | return (right-left +1)
16 |
17 | def main() {
18 | print(minimumLength("aabccabba"))
19 | print(minimumLength("cabaabac"))
20 | }
21 |
22 | main()
23 |
--------------------------------------------------------------------------------
/1750-Minimum-Length-of-String-After-Deleting-Similar-Ends/rs/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "rs"
3 | version = "0.1.0"
4 | edition = "2021"
5 |
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 |
8 | [dependencies]
9 |
--------------------------------------------------------------------------------
/1750-Minimum-Length-of-String-After-Deleting-Similar-Ends/rs/src/main.rs:
--------------------------------------------------------------------------------
1 | #[allow(unused)]
2 | fn main() {
3 | let s = String::from("ca");
4 | println!("{}", minimum_length(s));
5 | let s = String::from("cabaabac");
6 | println!("{}", minimum_length(s));
7 | let s = String::from("aabccabba");
8 | println!("answer => {}", minimum_length(s));
9 | }
10 |
11 |
12 | #[allow(unused)]
13 | pub fn minimum_length(s: String) -> i32 {
14 |
15 | let mut left = 0;
16 | let mut s_vec: Vec = s.chars().collect();
17 | let mut right = s_vec.len() - 1 ;
18 |
19 | while left < right {
20 | let same_ch = s_vec[left];
21 | if s_vec[left] == s_vec[right] {
22 | let same_ch = s_vec[left];
23 | while left<=right && s_vec[left] == same_ch {
24 | left += 1;
25 | }
26 | while left<=right && s_vec[right] == same_ch {
27 | right -= 1;
28 | }
29 |
30 | } else {
31 | break;
32 | }
33 | }
34 |
35 | (right-left +1) as i32
36 | }
37 |
--------------------------------------------------------------------------------
/1750-Minimum-Length-of-String-After-Deleting-Similar-Ends/ts/main.ts:
--------------------------------------------------------------------------------
1 | function minimumLength(s: string): number {
2 | let left = 0;
3 | let right = s.length -1 ;
4 |
5 | while (left < right) {
6 | if( s[left] == s[right]) {
7 | let same = s[left];
8 | while (left<=right && s[left] == same ) {
9 | left ++;
10 | }
11 | while (left<=right && s[right] == same ) {
12 | right --;
13 | }
14 | } else {
15 | break;
16 | }
17 | }
18 |
19 | return (right-left +1)
20 | };
21 |
22 |
23 |
24 | function main() {
25 | console.log(minimumLength("cabaabac"))
26 | }
27 |
28 | main()
29 |
--------------------------------------------------------------------------------
/234-Palindrome-Linked-List/desc.txt:
--------------------------------------------------------------------------------
1 | Given the head of a singly linked list, return true if it is a
2 | palindrome
3 | or false otherwise.
4 |
5 |
6 |
7 | Example 1:
8 |
9 | Input: head = [1,2,2,1]
10 | Output: true
11 |
12 | Example 2:
13 |
14 | Input: head = [1,2]
15 | Output: false
16 |
17 |
18 |
19 | Constraints:
20 |
21 | The number of nodes in the list is in the range [1, 105].
22 | 0 <= Node.val <= 9
23 |
24 |
25 |
--------------------------------------------------------------------------------
/234-Palindrome-Linked-List/go/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | )
6 |
7 | func main() {
8 | fmt.Println("Hello World")
9 | first := ListNode{
10 | Val: 1,
11 | Next: nil,
12 | }
13 |
14 | second := ListNode{
15 | Val: 2,
16 | Next: &first,
17 | }
18 | third := ListNode{
19 | Val: 2,
20 | Next: &second,
21 | }
22 | head := ListNode{
23 | Val: 1,
24 | Next: &third,
25 | }
26 |
27 | fmt.Println(isPalindrome(&head))
28 |
29 | }
30 |
31 | type ListNode struct {
32 | Val int
33 | Next *ListNode
34 | }
35 |
36 | func isPalindrome(head *ListNode) bool {
37 | var vecs []int
38 | for head != nil {
39 | fmt.Println(head.Val)
40 | vecs = append(vecs, head.Val)
41 | head = head.Next
42 | }
43 |
44 | first := 0
45 | length := len(vecs)
46 | last := length - 1
47 |
48 | for i := 0; i < length/2; i++ {
49 | if vecs[first] != vecs[last] {
50 | return false
51 | }
52 | first++
53 | last--
54 | }
55 | return true
56 | }
57 |
58 |
--------------------------------------------------------------------------------
/234-Palindrome-Linked-List/py/main.py:
--------------------------------------------------------------------------------
1 | class ListNode:
2 | def __init__(self, val=0, next=None):
3 | self.val = val
4 | self.next = next
5 |
6 | def is_palindrome(head: ListNode) -> bool:
7 | head_list = []
8 |
9 | while head:
10 | head_list.append(head.val)
11 | head = head.next
12 |
13 | first = 0
14 | length = len(head_list)
15 | last = length - 1
16 |
17 | i = 0
18 | loop_end = length // 2
19 | while i < loop_end:
20 | if head_list[first] != head_list[last]:
21 | return False
22 | first += 1
23 | last -= 1
24 | i += 1
25 |
26 | return True
27 |
--------------------------------------------------------------------------------
/234-Palindrome-Linked-List/rs/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "rs"
3 | version = "0.1.0"
4 | edition = "2021"
5 |
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 |
8 | [dependencies]
9 |
--------------------------------------------------------------------------------
/234-Palindrome-Linked-List/rs/src/main.rs:
--------------------------------------------------------------------------------
1 |
2 | #[derive(PartialEq, Eq, Clone, Debug)]
3 | pub struct ListNode {
4 | pub val: i32,
5 | pub next: Option>
6 | }
7 |
8 | impl ListNode {
9 | #[inline]
10 | fn new(val: i32) -> Self {
11 | ListNode {
12 | next: None,
13 | val
14 | }
15 | }
16 | }
17 |
18 | fn main() {
19 | let first = ListNode::new(1);
20 |
21 |
22 | let sec = ListNode{
23 | val: 2,
24 | next: Some(Box::new(first)),
25 | };
26 |
27 | let third = ListNode{
28 | val: 2,
29 | next: Some(Box::new(sec)),
30 | };
31 | let head = ListNode{
32 | val: 1,
33 | next: Some(Box::new(third)),
34 | };
35 |
36 | let answer = is_palindrome(Some(Box::new(head)));
37 | println!("{:?}", answer);
38 | }
39 |
40 |
41 |
42 |
43 | pub fn is_palindrome(mut head: Option>) -> bool {
44 |
45 | let mut head_vec: Vec = vec![] ;
46 |
47 | while let Some(node) = head {
48 | head_vec.push(node.val);
49 | head = node.next;
50 | }
51 |
52 | let mut first = 0;
53 | let mut length = head_vec.len();
54 | // let length = head_vec.len();
55 | let mut last = length-1;
56 |
57 | let mut i = 0;
58 | let loop_end = length/2;
59 | while i < loop_end {
60 | if head_vec[first] != head_vec[last]{
61 | return false;
62 | }
63 | first += 1;
64 | last -= 1;
65 | i += 1;
66 | }
67 | true
68 | }
69 |
--------------------------------------------------------------------------------
/234-Palindrome-Linked-List/ts/main.ts:
--------------------------------------------------------------------------------
1 | class ListNode {
2 | val: number;
3 | next: ListNode | null;
4 |
5 | constructor(val: number = 0, next: ListNode | null = null) {
6 | this.val = val;
7 | this.next = next;
8 | }
9 | }
10 |
11 | function isPalindrome(head: ListNode | null): boolean {
12 | let head_vec: number[] = [];
13 |
14 | while (head !== null) {
15 | head_vec.push(head.val);
16 | head = head.next;
17 | }
18 |
19 | let first = 0;
20 | let length = head_vec.length;
21 | let last = length - 1;
22 |
23 | let i = 0;
24 | let loop_end = Math.floor(length / 2);
25 | while (i < loop_end) {
26 | if (head_vec[first] !== head_vec[last]) {
27 | return false;
28 | }
29 | first++;
30 | last--;
31 | i++;
32 | }
33 |
34 | return true;
35 | }
36 |
--------------------------------------------------------------------------------
/2698-Find-the-Punishment-Number-of-an-Integer/desc.txt:
--------------------------------------------------------------------------------
1 | Given a positive integer n, return the punishment number of n.
2 |
3 | The punishment number of n is defined as the sum of the squares of all integers i such that:
4 |
5 | 1 <= i <= n
6 | The decimal representation of i * i can be partitioned into contiguous substrings such that the sum of the integer values of these substrings equals i.
7 |
8 |
9 |
10 | Example 1:
11 |
12 | Input: n = 10
13 | Output: 182
14 | Explanation: There are exactly 3 integers i in the range [1, 10] that satisfy the conditions in the statement:
15 | - 1 since 1 * 1 = 1
16 | - 9 since 9 * 9 = 81 and 81 can be partitioned into 8 and 1 with a sum equal to 8 + 1 == 9.
17 | - 10 since 10 * 10 = 100 and 100 can be partitioned into 10 and 0 with a sum equal to 10 + 0 == 10.
18 | Hence, the punishment number of 10 is 1 + 81 + 100 = 182
19 |
20 | Example 2:
21 |
22 | Input: n = 37
23 | Output: 1478
24 | Explanation: There are exactly 4 integers i in the range [1, 37] that satisfy the conditions in the statement:
25 | - 1 since 1 * 1 = 1.
26 | - 9 since 9 * 9 = 81 and 81 can be partitioned into 8 + 1.
27 | - 10 since 10 * 10 = 100 and 100 can be partitioned into 10 + 0.
28 | - 36 since 36 * 36 = 1296 and 1296 can be partitioned into 1 + 29 + 6.
29 | Hence, the punishment number of 37 is 1 + 81 + 100 + 1296 = 1478
30 |
31 |
32 |
33 | Constraints:
34 |
35 | 1 <= n <= 1000
36 |
37 |
--------------------------------------------------------------------------------
/2698-Find-the-Punishment-Number-of-an-Integer/go/main.go:
--------------------------------------------------------------------------------
1 |
2 | func punishmentNumber(n int) int {
3 | count := 0
4 | for i := 1; i <= n; i++ {
5 | if check(0, i, 0, strconv.Itoa(i*i)) {
6 | count += i * i
7 | }
8 | }
9 | return count
10 | }
11 |
12 | func check(idx, n, s int, s1 string) bool {
13 | if idx == len(s1) {
14 | if s == n {
15 | return true
16 | } else {
17 | return false
18 | }
19 | }
20 | for j := idx; j < len(s1); j++ {
21 | val, _ := strconv.Atoi(s1[idx : j+1])
22 | if check(j+1, n, s+val, s1) {
23 | return true
24 | }
25 | }
26 | return false
27 | }
--------------------------------------------------------------------------------
/2698-Find-the-Punishment-Number-of-an-Integer/rs/main.rs:
--------------------------------------------------------------------------------
1 | impl Solution {
2 | pub fn punishment_number(n: i32) -> i32 {
3 | let mut answer = 0;
4 | for i in 1..=n {
5 | answer += Self::calculate_punishment(i);
6 | }
7 | answer
8 | }
9 |
10 | fn calculate_punishment(n: i32) -> i32 {
11 | let sq = n * n;
12 | let sq_str = sq.to_string();
13 |
14 | let partitions = Self::generate_partitions(&sq_str);
15 |
16 | // Check each partition and calculate its sum
17 | for partition in partitions {
18 | let mut sum = 0;
19 | for part in partition {
20 | if let Ok(num) = part.parse::() {
21 | sum += num;
22 | }
23 | }
24 |
25 | // If the sum matches n, return the square
26 | if sum == n {
27 | return sq;
28 | }
29 | }
30 |
31 | 0
32 | }
33 |
34 | fn generate_partitions(s: &str) -> Vec> {
35 | let mut result = Vec::new();
36 | let mut partition = Vec::new();
37 | Self::helper(s, 0, &mut partition, &mut result);
38 | result
39 | }
40 |
41 | fn helper(s: &str, start: usize, partition: &mut Vec, result: &mut Vec>) {
42 | if start == s.len() {
43 | result.push(partition.clone());
44 | return;
45 | }
46 |
47 | // Loop to generate all partitions
48 | for i in start + 1..=s.len() {
49 | let substr = &s[start..i];
50 | partition.push(substr.to_string());
51 | Self::helper(s, i, partition, result);
52 | partition.pop(); // Backtrack
53 | }
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/2698-Find-the-Punishment-Number-of-an-Integer/ts/main.ts:
--------------------------------------------------------------------------------
1 | function punishmentNumber(n: number): number {
2 | let answer = 0;
3 |
4 | // Loop through all numbers from 1 to n
5 | for (let i = 1; i <= n; i++) {
6 | answer += calculatePunishment(i);
7 | }
8 | return answer;
9 | }
10 |
11 | // Helper function to calculate the punishment for each number
12 | function calculatePunishment(n: number): number {
13 | const sq = n * n;
14 | const sqStr = sq.toString();
15 |
16 | const partitions = generatePartitions(sqStr);
17 |
18 | // Check each partition to see if its sum matches n
19 | for (const partition of partitions) {
20 | let sum = 0;
21 | for (const part of partition) {
22 | const num = parseInt(part, 10);
23 | if (!isNaN(num)) {
24 | sum += num;
25 | }
26 | }
27 |
28 | // If the sum matches n, return the square
29 | if (sum === n) {
30 | return sq;
31 | }
32 | }
33 |
34 | return 0;
35 | }
36 |
37 | // Helper function to generate all partitions of a string
38 | function generatePartitions(s: string): string[][] {
39 | const result: string[][] = [];
40 | const partition: string[] = [];
41 | helper(s, 0, partition, result);
42 | return result;
43 | }
44 |
45 | // Recursive helper function to backtrack and generate partitions
46 | function helper(s: string, start: number, partition: string[], result: string[][]): void {
47 | if (start === s.length) {
48 | result.push([...partition]);
49 | return;
50 | }
51 |
52 | // Loop to generate all partitions
53 | for (let i = start + 1; i <= s.length; i++) {
54 | const substr = s.substring(start, i);
55 | partition.push(substr);
56 | helper(s, i, partition, result);
57 | partition.pop(); // Backtrack
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/2864-Maximum-Odd-Binary-Number/desc.txt:
--------------------------------------------------------------------------------
1 | You are given a binary string s that contains at least one '1'.
2 |
3 | You have to rearrange the bits in such a way that the resulting binary number is the maximum odd binary number that can be created from this combination.
4 |
5 | Return a string representing the maximum odd binary number that can be created from the given combination.
6 |
7 | Note that the resulting string can have leading zeros.
8 |
9 |
10 |
11 | Example 1:
12 |
13 | Input: s = "010"
14 | Output: "001"
15 | Explanation: Because there is just one '1', it must be in the last position. So the answer is "001".
16 |
17 | Example 2:
18 |
19 | Input: s = "0101"
20 | Output: "1001"
21 | Explanation: One of the '1's must be in the last position. The maximum number that can be made with the remaining digits is "100". So the answer is "1001".
22 |
23 |
24 |
25 | Constraints:
26 |
27 | 1 <= s.length <= 100
28 | s consists only of '0' and '1'.
29 | s contains at least one '1'.
30 |
31 |
--------------------------------------------------------------------------------
/2864-Maximum-Odd-Binary-Number/go/main.go:
--------------------------------------------------------------------------------
1 | func maximumOddBinaryNumber(s string) string {
2 | sthStr := s
3 | lenS := len(sthStr)
4 | var zeros []string
5 | var ones []string
6 |
7 | for _, char := range sthStr {
8 | if char == '1' {
9 | ones = append(ones, "1")
10 | } else {
11 | zeros = append(zeros, "0")
12 | }
13 | }
14 |
15 | switch len(ones) {
16 | case 0:
17 | return strings.Repeat("0", lenS)
18 | case 1:
19 | return strings.Repeat("0", lenS-1) + "1"
20 | default:
21 | ones = ones[:len(ones)-1]
22 | return strings.Join(ones, "") + strings.Join(zeros, "") + "1"
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/2864-Maximum-Odd-Binary-Number/py/main.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def maximumOddBinaryNumber(self, s: str) -> str:
3 | sth_str = s
4 | len_s = len(sth_str)
5 | zeros = []
6 | ones = []
7 |
8 | for char in sth_str:
9 | if char == '1':
10 | ones.append('1')
11 | else:
12 | zeros.append('0')
13 |
14 | if len(ones) == 0:
15 | return '0' * len_s
16 | elif len(ones) == 1:
17 | return '0' * (len_s - 1) + '1'
18 | else:
19 | ones.pop()
20 | return ''.join(ones) + ''.join(zeros) + '1'
21 |
--------------------------------------------------------------------------------
/2864-Maximum-Odd-Binary-Number/rs/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "rs"
3 | version = "0.1.0"
4 | edition = "2021"
5 |
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 |
8 | [dependencies]
9 |
--------------------------------------------------------------------------------
/2864-Maximum-Odd-Binary-Number/rs/src/main.rs:
--------------------------------------------------------------------------------
1 | fn main() {
2 | println!("{:?}", maximum_odd_bunary_number("100110010"));
3 | }
4 |
5 | pub fn maximum_odd_binary_number(s: String) -> String {
6 | let sth_str = s;
7 | let len_s = sth_str.len();
8 | let mut zeros = Vec::new();
9 | let mut ones = Vec::new();
10 |
11 | for char in sth_str.chars() {
12 | if char == '1' {
13 | ones.push('1');
14 | } else {
15 | zeros.push('0');
16 | }
17 | }
18 |
19 | match ones.len() {
20 | 0 => "0".repeat(len_s),
21 | 1 => "0".repeat(len_s - 1) + "1",
22 | _ => {
23 | ones.pop();
24 | ones.iter().collect::() + &zeros.iter().collect::() + "1"
25 | }
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/2864-Maximum-Odd-Binary-Number/ts/main.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @param {string} s
3 | * @return {string}
4 | */
5 | var maximumOddBinaryNumber = function(s) {
6 | let sth_str = s;
7 | let len = sth_str.length;
8 | let zeros = [];
9 | let ones = [];
10 |
11 | for (let i = 0; i < sth_str.length; i++) {
12 | if (sth_str[i] == '1') {
13 | ones.push('1');
14 | } else {
15 | zeros.push('0');
16 | }
17 | }
18 |
19 | let res;
20 | switch (ones.length) {
21 | case 0:
22 | res = new Array(len).fill("0").join('');
23 | return res;
24 | case 1:
25 | res = new Array(len - 1).fill("0").join('') + "1";
26 | return res;
27 | default:
28 | ones.pop();
29 | res = ones.join('') + zeros.join('') + "1";
30 | return res;
31 | }
32 | };
33 |
--------------------------------------------------------------------------------
/2864-Maximum-Odd-Binary-Number/ts/main.ts:
--------------------------------------------------------------------------------
1 | function maximumOddBinaryNumber(s: string): string {
2 | const sth_str = s;
3 | const len = sth_str.length;
4 | const zeros: string[] = [];
5 | const ones: string[] = [];
6 |
7 | for (let i = 0; i < sth_str.length; i++) {
8 | if (sth_str[i] === '1') {
9 | ones.push('1');
10 | } else {
11 | zeros.push('0');
12 | }
13 | }
14 |
15 | let res: string;
16 | switch (ones.length) {
17 | case 0:
18 | res = new Array(len).fill("0").join('');
19 | return res;
20 | case 1:
21 | res = new Array(len - 1).fill("0").join('') + "1";
22 | return res;
23 | default:
24 | ones.pop();
25 | res = ones.join('') + zeros.join('') + "1";
26 | return res;
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/287-Find-the-Duplicate-Number/go/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | func main(){
6 | fmt.Println("hello world")
7 | }
8 |
9 | func findDuplicate(nums []int) int {
10 | hasSeenNumber := make([]int, len(nums))
11 | for _, num := range nums {
12 | if hasSeenNumber[num] == -1 {
13 | return num
14 | }
15 | hasSeenNumber[num] = -1
16 | }
17 | return -1
18 | }
19 |
20 |
21 |
--------------------------------------------------------------------------------
/287-Find-the-Duplicate-Number/py/main.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def findDuplicate(self, nums):
3 | """
4 | :type nums: List[int]
5 | :rtype: int
6 | """
7 | hasSeenNumber = [0] * len(nums)
8 | for num in nums:
9 | if hasSeenNumber[num] == -1:
10 | return num
11 | hasSeenNumber[num] = -1
12 | return -1
13 |
--------------------------------------------------------------------------------
/287-Find-the-Duplicate-Number/rs/main.rs:
--------------------------------------------------------------------------------
1 | fm main() {
2 | println!("Hello workd");
3 | }
4 |
5 | pub fn find_duplicate(nums: Vec) -> i32 {
6 | let mut hasSeenNumber = nums.clone();
7 | for &num in nums.iter() {
8 | if hasSeenNumber[num as usize] == -1 {
9 | return num;
10 | }
11 | hasSeenNumber[num as usize] = -1;
12 | }
13 | return -1;
14 | }
15 |
--------------------------------------------------------------------------------
/287-Find-the-Duplicate-Number/ts/main.ts:
--------------------------------------------------------------------------------
1 | function findDuplicate(nums: number[]): number {
2 | let hasSeenNumber: number[] = new Array(nums.length).fill(0);
3 | for (let num of nums) {
4 | if (hasSeenNumber[num] === -1) {
5 | return num;
6 | }
7 | hasSeenNumber[num] = -1;
8 | }
9 | return -1;
10 | }
11 |
12 |
13 |
--------------------------------------------------------------------------------
/3005-Count-Elements-With-Maximum-Frequency/desc.txt:
--------------------------------------------------------------------------------
1 | You are given an array nums consisting of positive integers.
2 |
3 | Return the total frequencies of elements in nums such that those elements all have the maximum frequency.
4 |
5 | The frequency of an element is the number of occurrences of that element in the array.
6 |
7 |
8 |
9 | Example 1:
10 |
11 | Input: nums = [1,2,2,3,1,4]
12 | Output: 4
13 | Explanation: The elements 1 and 2 have a frequency of 2 which is the maximum frequency in the array.
14 | So the number of elements in the array with maximum frequency is 4.
15 |
16 | Example 2:
17 |
18 | Input: nums = [1,2,3,4,5]
19 | Output: 5
20 | Explanation: All elements of the array have a frequency of 1 which is the maximum.
21 | So the number of elements in the array with maximum frequency is 5.
22 |
23 |
24 |
25 | Constraints:
26 |
27 | 1 <= nums.length <= 100
28 | 1 <= nums[i] <= 100
29 |
30 |
--------------------------------------------------------------------------------
/3005-Count-Elements-With-Maximum-Frequency/go/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | )
6 |
7 | func maxFrequencyElements(nums []int) int {
8 | // Create a map to store frequency of elements
9 | freqMap := make(map[int]int)
10 |
11 | // Populate frequency map
12 | for _, val := range nums {
13 | freqMap[val]++
14 | }
15 |
16 | // Find maximum frequency
17 | max := -1
18 | for _, freq := range freqMap {
19 | if freq > max {
20 | max = freq
21 | }
22 | }
23 |
24 | // Calculate count of elements with maximum frequency
25 | count := 0
26 | for _, freq := range freqMap {
27 | if freq == max {
28 | count += max
29 | }
30 | }
31 |
32 | return count
33 | }
34 |
35 | func main() {
36 | nums := []int{1, 2, 2, 3, 3, 3}
37 | result := maxFrequencyElements(nums)
38 | fmt.Println("Result:", result)
39 | }
40 |
--------------------------------------------------------------------------------
/3005-Count-Elements-With-Maximum-Frequency/rs/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "rs"
3 | version = "0.1.0"
4 | edition = "2021"
5 |
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 |
8 | [dependencies]
9 |
--------------------------------------------------------------------------------
/3005-Count-Elements-With-Maximum-Frequency/rs/src/main.rs:
--------------------------------------------------------------------------------
1 | fn main() {
2 | println!("Hello, world!");
3 | }
4 |
5 |
6 | use std::collections::HashMap;
7 |
8 | pub fn max_frequency_elements(nums: Vec) -> i32 {
9 | let mut map = HashMap::new();
10 | for val in nums {
11 | let count = map.entry(val).or_insert(0);
12 | *count +=1;
13 | }
14 |
15 | let mut count = 0;
16 | let mut max = -1;
17 |
18 | for &freq in map.values() {
19 | max = max.max(freq);
20 | }
21 |
22 | for &freq in map.values() {
23 | if freq == max {
24 | count += max;
25 | }
26 | }
27 |
28 | count
29 | }
30 |
--------------------------------------------------------------------------------
/3005-Count-Elements-With-Maximum-Frequency/ts/main.ts:
--------------------------------------------------------------------------------
1 | function maxFrequencyElements(nums: number[]): number {
2 | // Create a map to store frequency of elements
3 | const freqMap: Map = new Map();
4 |
5 | // Populate frequency map
6 | for (const val of nums) {
7 | freqMap.set(val, (freqMap.get(val) || 0) + 1);
8 | }
9 |
10 | // Find maximum frequency
11 | let max = -1;
12 | for (const freq of freqMap.values()) {
13 | max = Math.max(max, freq);
14 | }
15 |
16 | // Calculate count of elements with maximum frequency
17 | let count = 0;
18 | for (const freq of freqMap.values()) {
19 | if (freq === max) {
20 | count += max;
21 | }
22 | }
23 |
24 | return count;
25 | }
26 |
27 | // Example usage:
28 | const nums: number[] = [1, 2, 2, 3, 3, 3];
29 | console.log(maxFrequencyElements(nums));
30 |
--------------------------------------------------------------------------------
/349-Intersection-of-Two-Arrays/desc.txt:
--------------------------------------------------------------------------------
1 | Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must be unique and you may return the result in any order.
2 |
3 |
4 |
5 | Example 1:
6 |
7 | Input: nums1 = [1,2,2,1], nums2 = [2,2]
8 | Output: [2]
9 |
10 | Example 2:
11 |
12 | Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
13 | Output: [9,4]
14 | Explanation: [4,9] is also accepted.
15 |
16 |
17 |
18 | Constraints:
19 |
20 | 1 <= nums1.length, nums2.length <= 1000
21 | 0 <= nums1[i], nums2[i] <= 1000
22 |
23 |
--------------------------------------------------------------------------------
/349-Intersection-of-Two-Arrays/go/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | func intersection(nums1 []int, nums2 []int) []int {
6 | m := make(map[int]bool)
7 | var res []int
8 |
9 | for _, num := range nums1 {
10 | m[num] = true
11 | }
12 |
13 | for _, num := range nums2 {
14 | if m[num] {
15 | res = append(res, num)
16 | delete(m, num)
17 | }
18 | }
19 |
20 | return res
21 | }
22 |
23 | func main() {
24 | nums1 := []int{1, 2, 2, 1}
25 | nums2 := []int{2, 2}
26 | fmt.Println(intersection(nums1, nums2))
27 | }
28 |
29 |
--------------------------------------------------------------------------------
/349-Intersection-of-Two-Arrays/py/main.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
3 | return list(set(nums1) & set(nums2))
4 |
--------------------------------------------------------------------------------
/349-Intersection-of-Two-Arrays/rs/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "rs"
3 | version = "0.1.0"
4 | edition = "2021"
5 |
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 |
8 | [dependencies]
9 |
--------------------------------------------------------------------------------
/349-Intersection-of-Two-Arrays/rs/src/main.rs:
--------------------------------------------------------------------------------
1 | fn main() {
2 | println!("Hello, world!");
3 | }
4 |
5 |
6 |
7 | use std::collections::HashSet;
8 |
9 | pub fn intersection(nums1: Vec, nums2: Vec) -> Vec {
10 | let set1: HashSet<_> = nums1.into_iter().collect();
11 | let set2: HashSet<_> = nums2.into_iter().collect();
12 | set1.intersection(&set2).cloned().collect()
13 | }
14 |
--------------------------------------------------------------------------------
/349-Intersection-of-Two-Arrays/ts/main.ts:
--------------------------------------------------------------------------------
1 | function intersection(nums1: number[], nums2: number[]): number[] {
2 | let set1 = new Set(nums1);
3 | let set2 = new Set(nums2);
4 | return [...set1].filter(item => set2.has(item));
5 | };
6 |
7 |
--------------------------------------------------------------------------------
/402-Remove-K-Digits/c/main.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 |
5 | char* removeKdigits(char* num, int k) {
6 | int len = strlen(num);
7 | char* result = (char*)malloc((len + 1) * sizeof(char)); // Allocate memory for result string
8 | int top = 0; // Stack pointer for result string
9 | int removed = 0; // Counter for removed digits
10 |
11 | for (int i = 0; i < len; i++) {
12 | char value = num[i];
13 |
14 | while (removed < k && top > 0 && result[top - 1] > value) {
15 | top--;
16 | removed++;
17 | }
18 | result[top++] = value;
19 | }
20 |
21 | // If there are still remaining digits to be removed
22 | while (removed < k) {
23 | top--;
24 | removed++;
25 | }
26 |
27 | // Skip leading zeros
28 | int leadingZeros = 0;
29 | while (result[leadingZeros] == '0') {
30 | leadingZeros++;
31 | }
32 |
33 | // Allocate memory for final result string
34 | char* finalResult = (char*)malloc((len + 1 - leadingZeros) * sizeof(char));
35 |
36 | // Copy the non-zero characters to final result
37 | int j = 0;
38 | for (int i = leadingZeros; i < top; i++) {
39 | finalResult[j++] = result[i];
40 | }
41 | finalResult[j] = '\0'; // Null-terminate the final result string
42 |
43 | free(result); // Free memory allocated for intermediate result
44 |
45 | // Check if the finalResult is empty, if so return "0"
46 | if (finalResult[0] == '\0') {
47 | free(finalResult);
48 | finalResult = (char*)malloc(2 * sizeof(char));
49 | finalResult[0] = '0';
50 | finalResult[1] = '\0';
51 | }
52 | return finalResult;
53 | }
54 |
55 | int main() {
56 | printf("Sss\n");
57 | char* number = "10200";
58 | int k = 1;
59 | char* result = removeKdigits(number, k);
60 | printf("%s\n", result);
61 | free(result); // Free memory allocated for result
62 | return 0;
63 | }
64 |
--------------------------------------------------------------------------------
/402-Remove-K-Digits/desc.txt:
--------------------------------------------------------------------------------
1 | Given string num representing a non-negative integer num, and an integer k, return the smallest possible integer after removing k digits from num.
2 |
3 |
4 |
5 | Example 1:
6 |
7 | Input: num = "1432219", k = 3
8 | Output: "1219"
9 | Explanation: Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest.
10 |
11 | Example 2:
12 |
13 | Input: num = "10200", k = 1
14 | Output: "200"
15 | Explanation: Remove the leading 1 and the number is 200. Note that the output must not contain leading zeroes.
16 |
17 | Example 3:
18 |
19 | Input: num = "10", k = 2
20 | Output: "0"
21 | Explanation: Remove all the digits from the number and it is left with nothing which is 0.
22 |
23 |
24 |
25 | Constraints:
26 |
27 | 1 <= k <= num.length <= 105
28 | num consists of only digits.
29 | num does not have any leading zeros except for the zero itself.
30 |
31 |
--------------------------------------------------------------------------------
/402-Remove-K-Digits/go/main.go:
--------------------------------------------------------------------------------
1 | package main()
2 |
3 |
4 | func main() {
5 | println(removeKdigits("12333", 3))
6 | }
7 |
8 |
9 | func removeKdigits(num string, k int) string {
10 | var result []byte
11 | var removed int
12 |
13 | for i := 0; i < len(num); i++ {
14 | value := num[i]
15 |
16 | for removed < k && len(result) > 0 && result[len(result)-1] > value {
17 | result = result[:len(result)-1]
18 | removed++
19 | }
20 | result = append(result, value)
21 | }
22 |
23 | // If there are still remaining digits to be removed
24 | for removed < k {
25 | result = result[:len(result)-1]
26 | removed++
27 | }
28 |
29 | // Skip leading zeros
30 | leadingZeros := 0
31 | for _, c := range result {
32 | if c == '0' {
33 | leadingZeros++
34 | } else {
35 | break
36 | }
37 | }
38 |
39 | finalResult := string(result[leadingZeros:])
40 | if finalResult == "" {
41 | return "0"
42 | }
43 | return finalResult
44 | }
45 |
--------------------------------------------------------------------------------
/402-Remove-K-Digits/py/main.py:
--------------------------------------------------------------------------------
1 | def remove_k_digits(num: str, k: int) -> str:
2 | result = []
3 | removed = 0
4 |
5 | for value in num:
6 | while removed < k and result and result[-1] > value:
7 | result.pop()
8 | removed += 1
9 | result.append(value)
10 |
11 | # If there are still remaining digits to be removed
12 | while removed < k:
13 | result.pop()
14 | removed += 1
15 |
16 | # Skip leading zeros
17 | leading_zeros = 0
18 | for c in result:
19 | if c == '0':
20 | leading_zeros += 1
21 | else:
22 | break
23 |
24 | final_result = ''.join(result[leading_zeros:])
25 | if final_result == "" :
26 | return "0"
27 | return final_result
28 |
29 | def main():
30 | print("Sss")
31 | number = "1234"
32 | result = remove_k_digits(number, 2)
33 | print(result)
34 |
35 | if __name__ == "__main__":
36 | main()
37 |
--------------------------------------------------------------------------------
/402-Remove-K-Digits/rs/main.rs:
--------------------------------------------------------------------------------
1 | fn main() {
2 |
3 | println!("helo world");
4 | }
5 |
6 | pub fn remove_kdigits(num: String, k: i32) -> String {
7 | let nums_vec: Vec = num.chars().collect();
8 | let mut result = Vec::new();
9 | let mut removed = 0;
10 |
11 | for &value in nums_vec.iter() {
12 | while removed < k && !result.is_empty() && result.last().unwrap() > &value {
13 | result.pop();
14 | removed += 1;
15 | }
16 | result.push(value);
17 | }
18 |
19 | // If there are still remaining digits to be removed
20 | while removed < k {
21 | result.pop();
22 | removed += 1;
23 | }
24 |
25 | // Skip leading zeros
26 | let mut leading_zeros = 0;
27 | for &c in &result {
28 | if c == '0' {
29 | leading_zeros += 1;
30 | } else {
31 | break;
32 | }
33 | }
34 |
35 | let final_result: String = result.iter().skip(leading_zeros).collect();
36 | if final_result == "" {
37 | return "0".to_string();
38 | }
39 | final_result
40 | }
41 |
--------------------------------------------------------------------------------
/402-Remove-K-Digits/ts/main.ts:
--------------------------------------------------------------------------------
1 | function removeKDigits(num: string, k: number): string {
2 | const result: string[] = [];
3 | let removed: number = 0;
4 |
5 | for (let i = 0; i < num.length; i++) {
6 | const value = num[i];
7 |
8 | while (removed < k && result.length > 0 && result[result.length - 1] > value) {
9 | result.pop();
10 | removed++;
11 | }
12 | result.push(value);
13 | }
14 |
15 | // If there are still remaining digits to be removed
16 | while (removed < k) {
17 | result.pop();
18 | removed++;
19 | }
20 |
21 | // Skip leading zeros
22 | let leadingZeros = 0;
23 | for (const c of result) {
24 | if (c === '0') {
25 | leadingZeros++;
26 | } else {
27 | break;
28 | }
29 | }
30 |
31 | const finalResult = result.slice(leadingZeros).join('');
32 | if(finalResult == ""){
33 | return "0";
34 | }
35 | return finalResult;
36 | }
37 |
38 | function main() {
39 | console.log("Sss");
40 | const number = "1234";
41 | const result = removeKDigits(number, 2);
42 | console.log(result);
43 | }
44 |
45 | main();
46 |
--------------------------------------------------------------------------------
/41-First-Missing-Positive/desc.txt:
--------------------------------------------------------------------------------
1 | Given an unsorted integer array nums. Return the smallest positive integer that is not present in nums.
2 |
3 | You must implement an algorithm that runs in O(n) time and uses O(1) auxiliary space.
4 |
5 |
6 |
7 | Example 1:
8 |
9 | Input: nums = [1,2,0]
10 | Output: 3
11 | Explanation: The numbers in the range [1,2] are all in the array.
12 |
13 | Example 2:
14 |
15 | Input: nums = [3,4,-1,1]
16 | Output: 2
17 | Explanation: 1 is in the array but 2 is missing.
18 |
19 | Example 3:
20 |
21 | Input: nums = [7,8,9,11,12]
22 | Output: 1
23 | Explanation: The smallest positive integer 1 is missing.
24 |
25 |
26 |
27 | Constraints:
28 |
29 | 1 <= nums.length <= 105
30 | -231 <= nums[i] <= 231 - 1
31 |
32 |
--------------------------------------------------------------------------------
/41-First-Missing-Positive/go/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | )
6 |
7 | func main() {
8 | fmt.Println("Hello World")
9 | nums := []int{
10 | 7,8,9,11,12,
11 | }
12 | fmt.Println(firstMissingPositive(nums))
13 | }
14 |
15 | func firstMissingPositive(nums []int) int {
16 | n := len(nums)
17 |
18 | for i:=0; i< n; i++ {
19 | if (nums[i] >= 1 &&
20 | nums[i] <= n &&
21 | nums[i] != nums[nums[i]-1]) {
22 | nums[i], nums[nums[i]-1] = nums[nums[i]-1], nums[i]
23 | i -= 1
24 | }
25 | }
26 |
27 | for i := range n {
28 | if nums[i] != i+1 {
29 | return i + 1
30 | }
31 | }
32 | return n + 1
33 | }
34 |
--------------------------------------------------------------------------------
/41-First-Missing-Positive/py/main.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def firstMissingPositive(self, nums: List[int]) -> int:
3 | n = len(nums)
4 |
5 | # Swap elements to their corresponding indices
6 | for i in range(n):
7 | while 1 <= nums[i] <= n and nums[nums[i] - 1] != nums[i]:
8 | nums[nums[i] - 1], nums[i] = nums[i], nums[nums[i] - 1]
9 |
10 | # Find the first missing positive integer
11 | for i in range(n):
12 | if nums[i] != i + 1:
13 | return i + 1
14 |
15 | return n + 1
16 |
--------------------------------------------------------------------------------
/41-First-Missing-Positive/rs/main.rs:
--------------------------------------------------------------------------------
1 | fn main() {
2 | let nums : Vec = vec![7,8,9,11,12];
3 | println!("{}", first_missing_positive(nums));
4 | }
5 |
6 | pub fn first_missing_positive(mut nums: Vec) -> i32 {
7 | let n = nums.len();
8 |
9 | for i in 0..n {
10 | while nums[i] >= 1 && nums[i] <= n as i32 && nums[i] != nums[(nums[i]-1) as usize] {
11 | let temp = nums[i];
12 | nums[i] = nums[(nums[i]-1) as usize];
13 | nums[(temp-1) as usize] = temp;
14 | }
15 | }
16 | for i in 0..n {
17 | if nums[i] != (i+1) as i32 {
18 | return (i + 1) as i32;
19 | }
20 | }
21 | (n+1) as i32
22 | }
23 |
24 |
--------------------------------------------------------------------------------
/41-First-Missing-Positive/ts/main.ts:
--------------------------------------------------------------------------------
1 | function firstMissingPositive(nums: number[]): number {
2 | let n = nums.length;
3 |
4 | for (let i = 0; i < n; i++) {
5 | while (nums[i] > 0 && nums[i] <= n && nums[nums[i] - 1] !== nums[i]) {
6 | let temp = nums[i];
7 | nums[i] = nums[nums[i] - 1];
8 | nums[temp - 1] = temp;
9 | }
10 | }
11 |
12 | for (let i = 0; i < n; i++) {
13 | if (nums[i] !== i + 1) {
14 | return i + 1;
15 | }
16 | }
17 |
18 | return n + 1;
19 | }
20 |
21 |
--------------------------------------------------------------------------------
/442-Find-All-Duplicates-in-an-Array/desc.txt:
--------------------------------------------------------------------------------
1 | Given an integer array nums of length n where all the integers of nums are in the range [1, n] and each integer appears once or twice, return an array of all the integers that appears twice.
2 |
3 | You must write an algorithm that runs in O(n) time and uses only constant extra space.
4 |
5 |
6 |
7 | Example 1:
8 |
9 | Input: nums = [4,3,2,7,8,2,3,1]
10 | Output: [2,3]
11 |
12 | Example 2:
13 |
14 | Input: nums = [1,1,2]
15 | Output: [1]
16 |
17 | Example 3:
18 |
19 | Input: nums = [1]
20 | Output: []
21 |
22 |
--------------------------------------------------------------------------------
/442-Find-All-Duplicates-in-an-Array/go/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "math"
6 | )
7 |
8 | func main() {
9 | fmt.Println("Hello World")
10 | nums := []int{
11 | 4, 3, 2, 7, 8, 2, 3, 1,
12 | }
13 | fmt.Println("duplicates =>", findDuplicates(nums))
14 | }
15 |
16 | func findDuplicates(nums []int) []int {
17 | var duplicates []int
18 |
19 | for _, num := range nums {
20 | index := int(math.Abs(float64(num))) - 1
21 |
22 | if nums[index] < 0 {
23 | duplicates = append(duplicates, int(math.Abs(float64(num))))
24 | } else {
25 | nums[index] = -nums[index]
26 | }
27 | }
28 | return duplicates
29 | }
30 |
--------------------------------------------------------------------------------
/442-Find-All-Duplicates-in-an-Array/py/main.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def findDuplicates(self, nums: List[int]) -> List[int]:
3 | duplicates = []
4 |
5 | for num in nums:
6 | # Get the absolute value of the number since we might have made it negative previously
7 | index = abs(num) - 1
8 |
9 | # If the value at index is negative, it means we've already seen this number before
10 | if nums[index] < 0:
11 | duplicates.append(index + 1)
12 | else:
13 | # Mark the number as visited by making its value negative
14 | nums[index] = -nums[index]
15 |
16 | return duplicates
17 |
--------------------------------------------------------------------------------
/442-Find-All-Duplicates-in-an-Array/rs/main.rs:
--------------------------------------------------------------------------------
1 | pub fn find_duplicates(mut nums: Vec) -> Vec {
2 | let mut dup_arr: Vec = vec![];
3 | let mut num_arr = nums.clone();
4 |
5 | for num in 0..nums.len() {
6 | let index = num_arr[num].abs() as usize - 1;
7 |
8 | if num_arr[index] < 0 {
9 | dup_arr.push(index as i32 + 1);
10 | }
11 | num_arr[index] *= -1;
12 | }
13 |
14 | dup_arr
15 | }
16 |
17 |
18 | fn main() {
19 | let nums: Vec = vec![4,3,2,7,8,2,3,1];
20 | find_duplicates(nums);
21 | }
22 |
--------------------------------------------------------------------------------
/442-Find-All-Duplicates-in-an-Array/ts/main.ts:
--------------------------------------------------------------------------------
1 | function findDuplicates(nums: number[]): number[] {
2 | const duplicates: number[] = [];
3 | nums.forEach((num) => {
4 | const index = Math.abs(num) - 1;
5 | if (nums[index] < 0) {
6 | duplicates.push(Math.abs(num));
7 | } else {
8 | nums[index] = -nums[index];
9 | }
10 | });
11 | return duplicates;
12 | }
13 |
--------------------------------------------------------------------------------
/452-Minimum-Number-of-Arrows-to-Burst-Balloons/desc.txt:
--------------------------------------------------------------------------------
1 | There are some spherical balloons taped onto a flat wall that represents the XY-plane. The balloons are represented as a 2D integer array points where points[i] = [xstart, xend] denotes a balloon whose horizontal diameter stretches between xstart and xend. You do not know the exact y-coordinates of the balloons.
2 |
3 | Arrows can be shot up directly vertically (in the positive y-direction) from different points along the x-axis. A balloon with xstart and xend is burst by an arrow shot at x if xstart <= x <= xend. There is no limit to the number of arrows that can be shot. A shot arrow keeps traveling up infinitely, bursting any balloons in its path.
4 |
5 | Given the array points, return the minimum number of arrows that must be shot to burst all balloons.
6 |
7 |
8 |
9 | Example 1:
10 |
11 | Input: points = [[10,16],[2,8],[1,6],[7,12]]
12 | Output: 2
13 | Explanation: The balloons can be burst by 2 arrows:
14 | - Shoot an arrow at x = 6, bursting the balloons [2,8] and [1,6].
15 | - Shoot an arrow at x = 11, bursting the balloons [10,16] and [7,12].
16 |
17 | Example 2:
18 |
19 | Input: points = [[1,2],[3,4],[5,6],[7,8]]
20 | Output: 4
21 | Explanation: One arrow needs to be shot for each balloon for a total of 4 arrows.
22 |
23 | Example 3:
24 |
25 | Input: points = [[1,2],[2,3],[3,4],[4,5]]
26 | Output: 2
27 | Explanation: The balloons can be burst by 2 arrows:
28 | - Shoot an arrow at x = 2, bursting the balloons [1,2] and [2,3].
29 | - Shoot an arrow at x = 4, bursting the balloons [3,4] and [4,5].
30 |
--------------------------------------------------------------------------------
/452-Minimum-Number-of-Arrows-to-Burst-Balloons/go/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "math"
6 | "sort"
7 | )
8 |
9 | func main() {
10 | fmt.Println("Hello World")
11 | points := [][]int{
12 | {10, 16},
13 | {2, 8},
14 | {1, 6},
15 | {7, 12},
16 | }
17 |
18 | arrows := findMinArrowShots(points)
19 | fmt.Println(arrows)
20 | }
21 |
22 | func findMinArrowShots(points [][]int) int {
23 | sort.Slice(points, func(i, j int) bool {
24 | return points[i][1] < points[j][1]
25 | })
26 |
27 | min := math.MinInt
28 | end := min
29 | arrows := 0
30 |
31 | for _, i := range points {
32 | if i[0] == min {
33 | if i[1] > end {
34 | arrows += 1
35 | end = i[1]
36 | }
37 | } else if i[0] > end {
38 | arrows += 1
39 | end = i[1]
40 | }
41 | }
42 | return arrows
43 | }
44 |
--------------------------------------------------------------------------------
/452-Minimum-Number-of-Arrows-to-Burst-Balloons/py/main.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def findMinArrowShots(self, points: List[List[int]]) -> int:
3 | if not points:
4 | return 0
5 |
6 | # Sort the points by the end of each interval
7 | points.sort(key=lambda x: x[1])
8 |
9 | min_val = float('-inf')
10 | end = min_val
11 | arrows = 0
12 |
13 | for i in points:
14 | if i[0] == min_val:
15 | if i[1] > end:
16 | arrows += 1
17 | end = i[1]
18 | elif i[0] > end:
19 | arrows += 1
20 | end = i[1]
21 |
22 | return arrows
23 |
--------------------------------------------------------------------------------
/452-Minimum-Number-of-Arrows-to-Burst-Balloons/rs/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "rs"
3 | version = "0.1.0"
4 | edition = "2021"
5 |
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 |
8 | [dependencies]
9 |
--------------------------------------------------------------------------------
/452-Minimum-Number-of-Arrows-to-Burst-Balloons/rs/src/main.rs:
--------------------------------------------------------------------------------
1 | fn main() {
2 | println!("Hello, world!");
3 | let points: Vec> = vec![vec![10,16],vec![2,8],vec![1,6],vec![7,12]];
4 | let points: Vec> = vec![vec![9,12],vec![1,10],vec![4,11],vec![8,12],vec![3,9],vec![6,9],vec![6,7]];
5 |
6 | println!("{}", find_min_arrow_shots(points));
7 |
8 | }
9 | pub fn find_min_arrow_shots(mut points: Vec>) -> i32 {
10 |
11 | points.sort_unstable_by_key(|v| v[1]);
12 |
13 | let min = std::i32::MIN;
14 | let mut end = min;
15 |
16 | let mut arrows = 0_i32 ;
17 |
18 | for i in points.iter() {
19 |
20 | if i[0] == min {
21 | if i[1] > end {
22 | arrows += 1;
23 | end = i[1];
24 | }
25 | }
26 |
27 | else if i[0] > end {
28 | arrows += 1;
29 | end = i[1];
30 | }
31 | }
32 |
33 | arrows
34 | }
35 |
--------------------------------------------------------------------------------
/452-Minimum-Number-of-Arrows-to-Burst-Balloons/ts/main.ts:
--------------------------------------------------------------------------------
1 | function findMinArrowShots(points: number[][]): number {
2 | if (points.length === 0) {
3 | return 0;
4 | }
5 |
6 | // Sort the points by the end of each interval
7 | points.sort((a, b) => a[1] - b[1]);
8 |
9 | let minVal = Number.NEGATIVE_INFINITY;
10 | let end = minVal;
11 | let arrows = 0;
12 |
13 | for (let i of points) {
14 | if (i[0] === minVal) {
15 | if (i[1] > end) {
16 | arrows += 1;
17 | end = i[1];
18 | }
19 | } else if (i[0] > end) {
20 | arrows += 1;
21 | end = i[1];
22 | }
23 | }
24 |
25 | return arrows;
26 | }
27 |
--------------------------------------------------------------------------------
/543-Diameter-of-Binary-Tree/desc.text:
--------------------------------------------------------------------------------
1 | Given the root of a binary tree, return the length of the diameter of the tree.
2 |
3 | The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.
4 |
5 | The length of a path between two nodes is represented by the number of edges between them.
6 |
7 |
8 |
9 | Example 1:
10 |
11 | Input: root = [1,2,3,4,5]
12 | Output: 3
13 | Explanation: 3 is the length of the path [4,2,1,3] or [5,2,1,3].
14 |
15 | Example 2:
16 |
17 | Input: root = [1,2]
18 | Output: 1
19 |
20 |
21 |
22 | Constraints:
23 |
24 | The number of nodes in the tree is in the range [1, 104].
25 | -100 <= Node.val <= 100
--------------------------------------------------------------------------------
/543-Diameter-of-Binary-Tree/go/main.go:
--------------------------------------------------------------------------------
1 | /**
2 | * Definition for a binary tree node.
3 | * type TreeNode struct {
4 | * Val int
5 | * Left *TreeNode
6 | * Right *TreeNode
7 | * }
8 | */
9 | // Function to calculate the diameter of a binary tree
10 | func diameterOfBinaryTree(root *TreeNode) int {
11 | var res = [1]int{0}
12 |
13 | var dfs func(node *TreeNode) int
14 | dfs = func(node *TreeNode) int {
15 | if node == nil {
16 | return -1
17 | }
18 |
19 | leftHeight := dfs(node.Left)
20 | rightHeight := dfs(node.Right)
21 |
22 | res[0] = max(res[0], 2+leftHeight+rightHeight)
23 |
24 | return 1 + max(leftHeight, rightHeight)
25 | }
26 |
27 | dfs(root)
28 | return res[0]
29 | }
30 |
31 | func max(a, b int) int {
32 | if a > b {
33 | return a
34 | }
35 | return b
36 | }
37 |
--------------------------------------------------------------------------------
/543-Diameter-of-Binary-Tree/py/main.py:
--------------------------------------------------------------------------------
1 | // Definition for a binary tree node.
2 | // #[derive(Debug, PartialEq, Eq)]
3 | // pub struct TreeNode {
4 | // pub val: i32,
5 | // pub left: Option>>,
6 | // pub right: Option>>,
7 | // }
8 | //
9 | // impl TreeNode {
10 | // #[inline]
11 | // pub fn new(val: i32) -> Self {
12 | // TreeNode {
13 | // val,
14 | // left: None,
15 | // right: None
16 | // }
17 | // }
18 | // }
19 | use std::rc::Rc;
20 | use std::cell::RefCell;
21 | impl Solution {
22 | pub fn diameter_of_binary_tree(root: Option>>) -> i32 {
23 | let mut res: Vec = vec![0];
24 |
25 | pub fn dfs(root: Option>>, res: &mut Vec) -> i32 {
26 | match root {
27 | None => -1,
28 | Some(n) => {
29 | let left = dfs(n.borrow().left.clone(), res);
30 | let right = dfs(n.borrow().right.clone(), res);
31 |
32 | let other = 2 + left + right;
33 | res[0] = res[0].max(other);
34 |
35 | 1 + left.max(right)
36 | }
37 | }
38 | }
39 | dfs(root, &mut res);
40 | res[0]
41 | }
42 | }
43 |
44 |
--------------------------------------------------------------------------------
/543-Diameter-of-Binary-Tree/rs/Cargo.lock:
--------------------------------------------------------------------------------
1 | # This file is automatically @generated by Cargo.
2 | # It is not intended for manual editing.
3 | version = 3
4 |
5 | [[package]]
6 | name = "rs"
7 | version = "0.1.0"
8 |
--------------------------------------------------------------------------------
/543-Diameter-of-Binary-Tree/rs/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "rs"
3 | version = "0.1.0"
4 | edition = "2021"
5 |
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 |
8 | [dependencies]
9 |
--------------------------------------------------------------------------------
/543-Diameter-of-Binary-Tree/rs/src/main.rs:
--------------------------------------------------------------------------------
1 | fn main() {
2 |
3 | }
4 |
5 | // Definition for a binary tree node.
6 | #[derive(Debug, PartialEq, Eq)]
7 | pub struct TreeNode {
8 | pub val: i32,
9 | pub left: Option>>,
10 | pub right: Option>>,
11 | }
12 |
13 | impl TreeNode {
14 | #[inline]
15 | pub fn new(val: i32) -> Self {
16 | TreeNode {
17 | val,
18 | left: None,
19 | right: None
20 | }
21 | }
22 | }
23 | use std::rc::Rc;
24 | use std::cell::RefCell;
25 |
26 | struct Solution{
27 |
28 | }
29 |
30 | impl Solution {
31 | pub fn diameter_of_binary_tree(root: Option>>) -> i32 {
32 | let mut res: Vec = vec![0];
33 |
34 | pub fn dfs(root: Option>>, res: &mut Vec) -> i32 {
35 | match root {
36 | None => -1,
37 | Some(n) => {
38 | let left = dfs(n.borrow().left.clone(), res);
39 | let right = dfs(n.borrow().right.clone(), res);
40 |
41 | let other = 2 + left + right;
42 | res[0] = res[0].max(other);
43 |
44 | 1 + left.max(right)
45 | }
46 | }
47 | }
48 | dfs(root, &mut res);
49 | res[0]
50 | }
51 | }
52 |
53 |
--------------------------------------------------------------------------------
/543-Diameter-of-Binary-Tree/ts/main.ts:
--------------------------------------------------------------------------------
1 |
2 | // Definition for a binary tree node.
3 | class TreeNode {
4 | val: number
5 | left: TreeNode | null
6 | right: TreeNode | null
7 | constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
8 | this.val = (val===undefined ? 0 : val)
9 | this.left = (left===undefined ? null : left)
10 | this.right = (right===undefined ? null : right)
11 | }
12 | }
13 |
14 |
15 | function diameterOfBinaryTree(root: TreeNode | null): number {
16 | let res:number[] = [0]
17 |
18 | function dfs (root: TreeNode | null) : number{
19 | if (root==null) {
20 | return -1;
21 | }
22 | let left = dfs(root.left);
23 | let right = dfs(root.right);
24 |
25 | res[0] = Math.max(res[0], (2+left+right) )
26 | return (1+ Math.max(left, right))
27 | }
28 | dfs(root);
29 | return res[0]
30 |
31 | };
32 |
33 |
--------------------------------------------------------------------------------
/876-Middle-of-the-Linked-List/desc.txt:
--------------------------------------------------------------------------------
1 | Given the head of a singly linked list, return the middle node of the linked list.
2 |
3 | If there are two middle nodes, return the second middle node.
4 |
5 |
6 |
7 | Example 1:
8 |
9 | Input: head = [1,2,3,4,5]
10 | Output: [3,4,5]
11 | Explanation: The middle node of the list is node 3.
12 |
13 | Example 2:
14 |
15 | Input: head = [1,2,3,4,5,6]
16 | Output: [4,5,6]
17 | Explanation: Since the list has two middle nodes with values 3 and 4, we return the second one.
18 |
19 |
20 |
21 | Constraints:
22 |
23 | The number of nodes in the list is in the range [1, 100].
24 | 1 <= Node.val <= 100
25 |
26 |
--------------------------------------------------------------------------------
/876-Middle-of-the-Linked-List/go/main.go:
--------------------------------------------------------------------------------
1 | /**
2 | * Definition for singly-linked list.
3 | * type ListNode struct {
4 | * Val int
5 | * Next *ListNode
6 | * }
7 | */
8 | func middleNode(head *ListNode) *ListNode {
9 | slow := head
10 | fast := head
11 |
12 | for fast != nil && fast.Next != nil {
13 | fast = fast.Next.Next
14 | slow = slow.Next
15 | }
16 |
17 | return slow
18 |
19 | }
20 |
--------------------------------------------------------------------------------
/876-Middle-of-the-Linked-List/py/main.py:
--------------------------------------------------------------------------------
1 | # Definition for singly-linked list.
2 | # class ListNode:
3 | # def __init__(self, val=0, next=None):
4 | # self.val = val
5 | # self.next = next
6 | class Solution:
7 | def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:
8 | fast = head
9 | slow = head
10 |
11 | while fast is not None and fast.next is not None:
12 | fast = fast.next.next
13 | slow = slow.next
14 |
15 | return slow
16 |
17 |
--------------------------------------------------------------------------------
/876-Middle-of-the-Linked-List/rs/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "rs"
3 | version = "0.1.0"
4 | edition = "2021"
5 |
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 |
8 | [dependencies]
9 |
--------------------------------------------------------------------------------
/876-Middle-of-the-Linked-List/rs/src/main.rs:
--------------------------------------------------------------------------------
1 | // Definition for singly-linked list.
2 | #[derive(PartialEq, Eq, Clone, Debug)]
3 | pub struct ListNode {
4 | pub val: i32,
5 | pub next: Option>
6 | }
7 |
8 | impl ListNode {
9 | #[inline]
10 | fn new(val: i32) -> Self {
11 | ListNode {
12 | next: None,
13 | val
14 | }
15 | }
16 | }
17 |
18 | pub fn middle_node(head: Option>) -> Option> {
19 | let mut fast = &head;
20 | let mut slow = & head;
21 |
22 | while fast.as_ref().and_then(|node| node.next.as_ref()).is_some() {
23 | slow = &slow.as_ref().unwrap().next;
24 | fast = &fast.as_ref().unwrap().next.as_ref().unwrap().next;
25 | }
26 |
27 | slow.clone()
28 | }
29 |
30 |
31 | fn main() {
32 | // create linked list with these items
33 | let node5 = Box::new(ListNode::new(5));
34 | let node4 = Box::new(ListNode {
35 | val: 4,
36 | next: Some(node5),
37 | });
38 | let node3 = Box::new(ListNode {
39 | val: 3,
40 | next: Some(node4),
41 | });
42 | let node2 = Box::new(ListNode {
43 | val: 2,
44 | next: Some(node3),
45 | });
46 | let head = Box::new(ListNode {
47 | val: 1,
48 | next: Some(node2),
49 | });
50 |
51 | let mid_one = middle_node(Some(head));
52 | println!("{:?}", mid_one);
53 | }
54 |
--------------------------------------------------------------------------------
/876-Middle-of-the-Linked-List/ts/main.ts:
--------------------------------------------------------------------------------
1 | /**
2 | * Definition for singly-linked list.
3 | * class ListNode {
4 | * val: number
5 | * next: ListNode | null
6 | * constructor(val?: number, next?: ListNode | null) {
7 | * this.val = (val===undefined ? 0 : val)
8 | * this.next = (next===undefined ? null : next)
9 | * }
10 | * }
11 | */
12 |
13 | function middleNode(head: ListNode | null): ListNode | null {
14 | let fast = head;
15 | let slow = head;
16 |
17 | while (fast != null && fast.next != null ) {
18 | fast = fast.next.next;
19 | slow = slow.next;
20 | }
21 |
22 | return slow;
23 | };
24 |
--------------------------------------------------------------------------------
/948-Bag-of-Token/desc.txt:
--------------------------------------------------------------------------------
1 | You start with an initial power of power, an initial score of 0, and a bag of tokens given as an integer array tokens, where each tokens[i] donates the value of tokeni.
2 |
3 | Your goal is to maximize the total score by strategically playing these tokens. In one move, you can play an unplayed token in one of the two ways (but not both for the same token):
4 |
5 | Face-up: If your current power is at least tokens[i], you may play tokeni, losing tokens[i] power and gaining 1 score.
6 | Face-down: If your current score is at least 1, you may play tokeni, gaining tokens[i] power and losing 1 score.
7 |
8 | Return the maximum possible score you can achieve after playing any number of tokens.
9 |
10 |
11 |
12 | Example 1:
13 |
14 | Input: tokens = [100], power = 50
15 |
16 | Output: 0
17 |
18 | Explanation: Since your score is 0 initially, you cannot play the token face-down. You also cannot play it face-up since your power (50) is less than tokens[0] (100).
19 |
20 | Example 2:
21 |
22 | Input: tokens = [200,100], power = 150
23 |
24 | Output: 1
25 |
26 | Explanation: Play token1 (100) face-up, reducing your power to 50 and increasing your score to 1.
27 |
28 | There is no need to play token0, since you cannot play it face-up to add to your score. The maximum score achievable is 1.
29 |
30 | Example 3:
31 |
32 | Input: tokens = [100,200,300,400], power = 200
33 |
34 | Output: 2
35 |
36 | Explanation: Play the tokens in this order to get a score of 2:
37 |
38 | Play token0 (100) face-up, reducing power to 100 and increasing score to 1.
39 | Play token3 (400) face-down, increasing power to 500 and reducing score to 0.
40 | Play token1 (200) face-up, reducing power to 300 and increasing score to 1.
41 | Play token2 (300) face-up, reducing power to 0 and increasing score to 2.
42 |
43 | The maximum score achievable is 2.
44 |
45 |
46 |
47 | Constraints:
48 |
49 | 0 <= tokens.length <= 1000
50 | 0 <= tokens[i], power < 104
51 |
52 |
--------------------------------------------------------------------------------
/948-Bag-of-Token/go/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "math"
6 | "sort"
7 | )
8 |
9 | func main() {
10 | fmt.Println("Hello World")
11 | tokens := []int{100, 200, 300, 400}
12 | power := 200
13 | fmt.Println(bagOfTokensScore(tokens, power))
14 | }
15 |
16 | func bagOfTokensScore(tokens []int, power int) int {
17 | sort.Ints(tokens)
18 |
19 | left := 0
20 | right := len(tokens) - 1
21 |
22 | score := 0
23 | max_score := 0
24 |
25 | for left <= right {
26 | if tokens[left] <= power {
27 | power -= tokens[left]
28 | left += 1
29 | score += 1
30 | max_score = int(math.Max(float64(max_score), float64(score)))
31 | } else if score > 0 {
32 | power += tokens[right]
33 | right -= 1
34 | score -= 1
35 | } else {
36 | break
37 | }
38 | }
39 |
40 | return max_score
41 | }
42 |
--------------------------------------------------------------------------------
/948-Bag-of-Token/py/main.py:
--------------------------------------------------------------------------------
1 | from typing import List
2 |
3 | class Solution:
4 | def bagOfTokensScore(self, tokens: List[int], power: int) -> int:
5 | tokens.sort()
6 |
7 | left = 0
8 | right = len(tokens) - 1
9 |
10 | score = 0
11 | max_score = 0
12 |
13 | while left <= right:
14 | if tokens[left] <= power:
15 | power -= tokens[left]
16 | left += 1
17 | score += 1
18 | max_score = max(max_score, score)
19 | elif score > 0:
20 | power += tokens[right]
21 | right -= 1
22 | score -= 1
23 | else:
24 | break
25 |
26 | return max_score
27 |
--------------------------------------------------------------------------------
/948-Bag-of-Token/rs/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "rs"
3 | version = "0.1.0"
4 | edition = "2021"
5 |
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 |
8 | [dependencies]
9 |
--------------------------------------------------------------------------------
/948-Bag-of-Token/rs/src/main.rs:
--------------------------------------------------------------------------------
1 | #[allow(unused)]
2 | fn main() {
3 | println!("Hello, world!");
4 | // let tokens: Vec = vec![100];
5 | // let power: i32 = 50;
6 |
7 | // let tokens: Vec = vec![200,100];
8 | // let power: i32 = 150;
9 |
10 | let tokens: Vec = vec![100,200,300,400];
11 | let power: i32 = 200;
12 |
13 | println!("score => {:?}", bag_of_tokens_score(tokens, power));
14 | }
15 |
16 | use std::cmp;
17 |
18 | #[allow(unused)]
19 | pub fn bag_of_tokens_score( tokens: Vec, power: i32) -> i32 {
20 | let mut tokens: Vec = tokens;
21 | let mut power = power;
22 |
23 | println!("{:?}", tokens);
24 | tokens.sort();
25 | println!("{:?}", tokens);
26 | let length = tokens.len();
27 | let mut left = 0;
28 | let mut right = length-1;
29 |
30 | let mut score: i32 = 0;
31 | let mut max_score: i32 = 0;
32 |
33 | while (left <= right) {
34 | println!();
35 | println!("left => {left}, right => {right}, length => {length}");
36 | println!("score => {score}, max_score => {max_score}");
37 | if tokens[left] <= power {
38 | println!("if");
39 | power -= tokens[left];
40 | left += 1;
41 | score += 1;
42 | max_score = cmp::max(max_score, score);
43 | }
44 | else if score > 0 {
45 | println!("else if");
46 | power += tokens[right];
47 | right -= 1;
48 | score -= 1;
49 | }
50 | else {
51 | break
52 | }
53 |
54 | }
55 | max_score
56 | }
57 |
--------------------------------------------------------------------------------
/948-Bag-of-Token/ts/main.ts:
--------------------------------------------------------------------------------
1 | function bagOfTokensScore(tokens: number[], power: number): number {
2 | tokens.sort((a, b) => a - b);
3 |
4 | let left = 0;
5 | let right = tokens.length - 1;
6 |
7 | let score = 0;
8 | let max_score = 0;
9 |
10 | while (left <= right) {
11 | if (tokens[left] <= power) {
12 | power -= tokens[left];
13 | left++;
14 | score++;
15 | max_score = Math.max(max_score, score);
16 | } else if (score > 0) {
17 | power += tokens[right];
18 | right--;
19 | score--;
20 | } else {
21 | break;
22 | }
23 | }
24 |
25 | return max_score;
26 | }
27 |
--------------------------------------------------------------------------------
/Cheapest-Flights-Within-K-Stops/desc.txt:
--------------------------------------------------------------------------------
1 | There are n cities connected by some number of flights. You are given an array flights where flights[i] = [fromi, toi, pricei] indicates that there is a flight from city fromi to city toi with cost pricei.
2 |
3 | You are also given three integers src, dst, and k, return the cheapest price from src to dst with at most k stops. If there is no such route, return -1.
4 |
5 |
6 |
7 | Example 1:
8 |
9 |
10 | Input: n = 4, flights = [[0,1,100],[1,2,100],[2,0,100],[1,3,600],[2,3,200]], src = 0, dst = 3, k = 1
11 | Output: 700
12 | Explanation:
13 | The graph is shown above.
14 | The optimal path with at most 1 stop from city 0 to 3 is marked in red and has cost 100 + 600 = 700.
15 | Note that the path through cities [0,1,2,3] is cheaper but is invalid because it uses 2 stops.
16 | Example 2:
17 |
18 |
19 | Input: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 1
20 | Output: 200
21 | Explanation:
22 | The graph is shown above.
23 | The optimal path with at most 1 stop from city 0 to 2 is marked in red and has cost 100 + 100 = 200.
24 | Example 3:
25 |
26 |
27 | Input: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 0
28 | Output: 500
29 | Explanation:
30 | The graph is shown above.
31 | The optimal path with no stops from city 0 to 2 is marked in red and has cost 500.
32 |
33 |
34 | Constraints:
35 |
36 | 1 <= n <= 100
37 | 0 <= flights.length <= (n * (n - 1) / 2)
38 | flights[i].length == 3
39 | 0 <= fromi, toi < n
40 | fromi != toi
41 | 1 <= pricei <= 104
42 | There will not be any multiple flights between two cities.
43 | 0 <= src, dst, k < n
44 | src != dst
--------------------------------------------------------------------------------
/Cheapest-Flights-Within-K-Stops/py/main.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, k: int) -> int:
3 | prices = [float("inf")] * n
4 | prices[src] = 0
5 |
6 | for i in range (k + 1):
7 | tempPrices = prices.copy()
8 |
9 | for s, d, p in flights: # s: source, d: destination, p: price
10 | if prices[s] == float("inf"):
11 | continue
12 | if prices[s] + p < tempPrices[d]:
13 | tempPrices[d] = prices[s] + p
14 | prices = tempPrices
15 |
16 | return -1 if prices[dst] == float("inf") else prices[dst]
--------------------------------------------------------------------------------
/Cheapest-Flights-Within-K-Stops/rust/Cargo.lock:
--------------------------------------------------------------------------------
1 | # This file is automatically @generated by Cargo.
2 | # It is not intended for manual editing.
3 | version = 3
4 |
5 | [[package]]
6 | name = "rust"
7 | version = "0.1.0"
8 |
--------------------------------------------------------------------------------
/Cheapest-Flights-Within-K-Stops/rust/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "rust"
3 | version = "0.1.0"
4 | edition = "2021"
5 |
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 |
8 | [dependencies]
9 |
--------------------------------------------------------------------------------
/Cheapest-Flights-Within-K-Stops/rust/src/main.rs:
--------------------------------------------------------------------------------
1 | use std::f32;
2 |
3 | #[allow(unused)]
4 | fn main() {
5 | let n: i32 = 4;
6 | let flights: Vec> = vec![vec![0,1,100],vec![1,2,100],vec![2,0,100],vec![1,3,600],vec![2,3,200]];
7 | let src: i32 = 0;
8 | let dst: i32 = 3;
9 | let k: i32 = 1;
10 | let answer = find_cheapest_price(n, flights, src, dst, k);
11 | }
12 |
13 | #[allow(unused)]
14 | pub fn find_cheapest_price(n: i32, flights: Vec>, src: i32, dst: i32, k: i32) -> i32 {
15 | let n_usize = n as usize;
16 | let src_usize = src as usize;
17 | let dst_usize = dst as usize;
18 | let mut prices = vec![f32::INFINITY; n_usize];
19 | prices[src_usize] = 0.0;
20 |
21 | for _ in 0..=k {
22 | let mut temp_prices = prices.clone();
23 |
24 | for flight in &flights {
25 | let s = flight[0] as usize; // source
26 | let d = flight[1] as usize; // destination
27 | let p = flight[2] as f32; // price
28 |
29 | if prices[s] == f32::INFINITY {
30 | continue;
31 | }
32 |
33 | if prices[s] + p < temp_prices[d] {
34 | temp_prices[d] = prices[s] + p;
35 | }
36 | }
37 |
38 | prices = temp_prices;
39 | }
40 |
41 | if prices[dst_usize] == f32::INFINITY {
42 | return -1_i32;
43 | }
44 | return prices[dst_usize] as i32;
45 |
46 | }
47 |
--------------------------------------------------------------------------------
/Find-the-Town-Judge/desc.txt:
--------------------------------------------------------------------------------
1 | In a town, there are n people labeled from 1 to n. There is a rumor that one of these people is secretly the town judge.
2 |
3 | If the town judge exists, then:
4 |
5 | The town judge trusts nobody.
6 | Everybody (except for the town judge) trusts the town judge.
7 | There is exactly one person that satisfies properties 1 and 2.
8 |
9 | You are given an array trust where trust[i] = [ai, bi] representing that the person labeled ai trusts the person labeled bi. If a trust relationship does not exist in trust array, then such a trust relationship does not exist.
10 |
11 | Return the label of the town judge if the town judge exists and can be identified, or return -1 otherwise.
12 |
13 |
14 |
15 | Example 1:
16 |
17 | Input: n = 2, trust = [[1,2]]
18 | Output: 2
19 |
20 | Example 2:
21 |
22 | Input: n = 3, trust = [[1,3],[2,3]]
23 | Output: 3
24 |
25 | Example 3:
26 |
27 | Input: n = 3, trust = [[1,3],[2,3],[3,1]]
28 | Output: -1
29 |
30 |
--------------------------------------------------------------------------------
/Find-the-Town-Judge/go/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | func findJudge(n int, trust [][]int) int {
6 | trustCounts := make([]int, n+1)
7 |
8 | for _, t := range trust {
9 | trustCounts[t[0]]--
10 | trustCounts[t[1]]++
11 | }
12 |
13 | for i := 1; i <= n; i++ {
14 | if trustCounts[i] == n-1 {
15 | return i
16 | }
17 | }
18 |
19 | return -1
20 | }
21 |
22 | func main() {
23 | trust := [][]int{{1, 2}}
24 | n := 2
25 |
26 | answer := findJudge(n, trust)
27 | fmt.Println(answer)
28 | }
29 |
--------------------------------------------------------------------------------
/Find-the-Town-Judge/rust/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "Find-the-Town-Judge"
3 | version = "0.1.0"
4 | edition = "2021"
5 |
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 |
8 | [dependencies]
9 |
--------------------------------------------------------------------------------
/Find-the-Town-Judge/rust/src/main.rs:
--------------------------------------------------------------------------------
1 | use std::collections::HashMap;
2 |
3 | #[allow(unused)]
4 | fn main () {
5 | let n: i32 = 2;
6 | let trust: Vec> = vec![vec![1,2]];
7 |
8 | let n: i32 = 3;
9 | // let trust: Vec> = vec![vec![1,3],vec![2,3]];
10 | // let trust: Vec> = vec![vec![1,2],vec![2,3]];
11 | // let trust: Vec> = vec![vec![1,3],vec![1,4],vec![2,3],vec![2,4],vec![4,3]];
12 | let trust: Vec> = vec![vec![1,3],vec![2,3],vec![3,1]]; let n: i32 = 3;
13 | println!("{}", find_judge(n, trust));
14 | }
15 |
16 |
17 | #[allow(unused)]
18 | pub fn find_judge(n: i32, trust: Vec>) -> i32 {
19 | if trust.len() < 1 {
20 | if n == 1 {
21 | return 1_i32
22 | }
23 | return -1_i32
24 | }
25 | let mut trust_map: HashMap> = HashMap::new();
26 | let mut people: Vec = vec![];
27 |
28 | for item in trust {
29 | if ! people.iter().any(|x| *x==item[0]) {
30 | people.push(item[0]);
31 | }
32 | if ! people.iter().any(|x| *x==item[1]) {
33 | people.push(item[1]);
34 | }
35 | let key = item[1] ;
36 | if let Some(values) = trust_map.get_mut(&key){
37 | values.push(item[0]);
38 | } else {
39 | trust_map.insert(item[1], vec![item[0]]);
40 | }
41 | }
42 | let to_be_trusted_by = people.len() -1;
43 |
44 | for (key, val) in trust_map.iter() {
45 | if val.len() == to_be_trusted_by {
46 | if trust_map.values().any(|v| v.contains(&key)) {
47 | continue;
48 | }
49 | return *key;
50 | }
51 | }
52 | -1_i32
53 | }
54 |
55 |
--------------------------------------------------------------------------------
/Find-the-Town-Judge/ts/main.ts:
--------------------------------------------------------------------------------
1 | function findJudge(n: number, trust: number[][]): number {
2 | let trustCounts = new Array(n + 1).fill(0);
3 |
4 | trust.forEach(([truster, trustee]) => {
5 | trustCounts[truster]--;
6 | trustCounts[trustee]++;
7 | });
8 |
9 | for (let i = 1; i <= n; i++) {
10 | if (trustCounts[i] === n - 1) {
11 | return i;
12 | }
13 | }
14 |
15 | return -1;
16 | }
17 |
18 | function main() {
19 | let trust = [[1,2]];
20 | let n = 2;
21 |
22 | let answer = findJudge(n, trust);
23 | console.log(answer);
24 | }
25 |
26 | main();
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/high-horse/leetcode-solutions/41111825e75be64064c18186f72b668adb264442/README.md
--------------------------------------------------------------------------------
/bitwise-AND-of-number-range/Rust/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "bitwise-AND-of-number-range"
3 | version = "0.1.0"
4 | edition = "2021"
5 |
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 |
8 | [dependencies]
9 |
--------------------------------------------------------------------------------
/bitwise-AND-of-number-range/Rust/src/main.rs:
--------------------------------------------------------------------------------
1 |
2 | #[allow(unused)]
3 | fn main () {
4 | let (left , right) = ( 5_i32, 7_i32);
5 | let result = range_bitwise_and(left, right);
6 | println!("{:?}", result);
7 | println!("");
8 | println!("");
9 | let (left , right) = ( 0_i32, 0_i32);
10 | let result = range_bitwise_and(left, right);
11 | println!("{:?}", result);
12 | println!("");println!("");
13 |
14 | let (left , right) = ( 1_i32, 2147483647_i32);
15 | let result = range_bitwise_and(left, right);
16 | println!("{:?}", result);
17 | }
18 |
19 |
20 | #[allow(unused)]
21 | pub fn range_bitwise_and_(left: i32, right: i32) -> i32 {
22 | if left == right {
23 | return left;
24 | }
25 | let mut res:i32 = left;
26 | for i in (left..=right) {
27 | res = res & i;
28 | }
29 |
30 | res
31 | }
32 |
33 | #[allow(unused)]
34 | pub fn range_bitwise_and(mut left: i32, mut right: i32) -> i32 {
35 |
36 | while left < right {
37 | println!("{}", right);
38 | right &= right-1;
39 |
40 | }
41 | // for i in (left..=right) {
42 | // res = res & i;
43 | // }
44 |
45 | right
46 | }
47 |
48 |
49 |
--------------------------------------------------------------------------------
/bitwise-AND-of-number-range/desc.txt:
--------------------------------------------------------------------------------
1 | Given two integers left and right that represent the range [left, right], return the bitwise AND of all numbers in this range, inclusive.
2 |
3 |
4 |
5 | Example 1:
6 |
7 | Input: left = 5, right = 7
8 | Output: 4
9 |
10 | Example 2:
11 |
12 | Input: left = 0, right = 0
13 | Output: 0
14 |
15 | Example 3:
16 |
17 | Input: left = 1, right = 2147483647
18 | Output: 0
19 |
20 |
21 |
22 | Constraints:
23 |
24 | 0 <= left <= right <= 231 - 1
25 |
26 |
--------------------------------------------------------------------------------
/bitwise-AND-of-number-range/go/main.go:
--------------------------------------------------------------------------------
1 | package main
2 | import "fmt"
3 |
4 | func main() {
5 | var result_1 int = rangeBitwiseAnd(5, 7);
6 | fmt.Println(result_1);
7 |
8 | var result_2 int = rangeBitwiseAnd(0, 0);
9 | fmt.Println(result_2);
10 |
11 | var result_3 int = rangeBitwiseAnd(1, 2147483647);
12 | fmt.Println(result_3);
13 |
14 | }
15 |
16 | func rangeBitwiseAnd(left int, right int) int {
17 | for (left < right) {
18 | right &= right-1;
19 | }
20 | return right;
21 | }
--------------------------------------------------------------------------------
/bitwise-AND-of-number-range/py/main.py:
--------------------------------------------------------------------------------
1 | def rangeBitwiseAnd(self, left: int, right: int) -> int:
2 | while left < right :
3 | right &= right-1
4 |
5 | return right
6 |
7 |
8 | print(rangeBitwiseAnd(5,7))
9 | print(rangeBitwiseAnd(0, 0))
10 | print(rangeBitwiseAnd(1, 2147483647))
11 |
12 |
--------------------------------------------------------------------------------
/bitwise-AND-of-number-range/ts/main.ts:
--------------------------------------------------------------------------------
1 | function rangeBitwiseAnd(left: number, right: number): number {
2 | while (left < right) {
3 | right &= right-1
4 | }
5 | return right
6 | };
7 |
8 | console.log(rangeBitwiseAnd(5,7))
9 |
10 | console.log(rangeBitwiseAnd(0, 0))
11 |
12 | console.log(rangeBitwiseAnd(1, 2147483647))
--------------------------------------------------------------------------------
/cherry-pickup-II-py/desc.txt:
--------------------------------------------------------------------------------
1 | You are given a rows x cols matrix grid representing a field of cherries where grid[i][j] represents the number of cherries that you can collect from the (i, j) cell.
2 |
3 | You have two robots that can collect cherries for you:
4 |
5 | Robot #1 is located at the top-left corner (0, 0), and
6 | Robot #2 is located at the top-right corner (0, cols - 1).
7 |
8 | Return the maximum number of cherries collection using both robots by following the rules below:
9 |
10 | From a cell (i, j), robots can move to cell (i + 1, j - 1), (i + 1, j), or (i + 1, j + 1).
11 | When any robot passes through a cell, It picks up all cherries, and the cell becomes an empty cell.
12 | When both robots stay in the same cell, only one takes the cherries.
13 | Both robots cannot move outside of the grid at any moment.
14 | Both robots should reach the bottom row in grid.
15 |
16 |
17 |
18 | Example 1:
19 |
20 | Input: grid = [[3,1,1],[2,5,1],[1,5,5],[2,1,1]]
21 | Output: 24
22 | Explanation: Path of robot #1 and #2 are described in color green and blue respectively.
23 | Cherries taken by Robot #1, (3 + 2 + 5 + 2) = 12.
24 | Cherries taken by Robot #2, (1 + 5 + 5 + 1) = 12.
25 | Total of cherries: 12 + 12 = 24.
26 |
27 | Example 2:
28 |
29 | Input: grid = [[1,0,0,0,0,0,1],[2,0,0,0,0,3,0],[2,0,9,0,0,0,0],[0,3,0,5,4,0,0],[1,0,2,3,0,0,6]]
30 | Output: 28
31 | Explanation: Path of robot #1 and #2 are described in color green and blue respectively.
32 | Cherries taken by Robot #1, (1 + 9 + 5 + 2) = 17.
33 | Cherries taken by Robot #2, (1 + 3 + 4 + 3) = 11.
34 | Total of cherries: 17 + 11 = 28.
35 |
--------------------------------------------------------------------------------
/cherry-pickup-II-py/main.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def cherryPickup(self, grid):
3 | ROWS, COLS = len(grid), len(grid[0])
4 | cache = {}
5 |
6 | def dfs(r, c1, c2):
7 | if(r, c1, c2) in cache :
8 | return cache[(r, c1, c2)]
9 | if c1 == c2 or min(c1, c2) < 0 or max(c1, c2) == COLS:
10 | return 0
11 | if r == ROWS -1 :
12 | return grid[r][c1] + grid[r][c2]
13 |
14 | res = 0
15 | for c1_d in [-1, 0, +1]:
16 | for c2_d in [-1, 0, +1]:
17 | res = max(
18 | res,
19 | dfs(r+1, c1+c1_d, c2+c2_d)
20 | )
21 | cache[(r, c1, c2)] = res + grid[r][c1] + grid[r][c2]
22 | return cache[(r, c1, c2)]
23 |
24 | return dfs(0, 0, COLS-1)
--------------------------------------------------------------------------------
/find-first-palindromic-string-in-array/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "find-first-palindromic-string-in-array"
3 | version = "0.1.0"
4 | edition = "2021"
5 |
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 |
8 | [dependencies]
9 |
--------------------------------------------------------------------------------
/find-first-palindromic-string-in-array/desc.txt:
--------------------------------------------------------------------------------
1 | Given an array of strings words, return the first palindromic string in the array. If there is no such string, return an empty string "".
2 |
3 | A string is palindromic if it reads the same forward and backward.
4 |
5 |
6 |
7 | Example 1:
8 |
9 | Input: words = ["abc","car","ada","racecar","cool"]
10 | Output: "ada"
11 | Explanation: The first string that is palindromic is "ada".
12 | Note that "racecar" is also palindromic, but it is not the first.
13 |
14 | Example 2:
15 |
16 | Input: words = ["notapalindrome","racecar"]
17 | Output: "racecar"
18 | Explanation: The first and only string that is palindromic is "racecar".
19 |
20 | Example 3:
21 |
22 | Input: words = ["def","ghi"]
23 | Output: ""
24 | Explanation: There are no palindromic strings, so the empty string is returned.
25 |
--------------------------------------------------------------------------------
/find-first-palindromic-string-in-array/src/main.rs:
--------------------------------------------------------------------------------
1 | #[allow(unused)]
2 | pub fn first_palindrome(words: Vec) -> String {
3 | for word in words.iter() {
4 | let vec_word: Vec = word.chars().collect();
5 |
6 | let mut first_index = 0;
7 | let mut last_index = word.len()-1;
8 |
9 | while first_index < last_index {
10 | if vec_word[first_index] != vec_word[last_index] {
11 | break;
12 | }
13 | first_index += 1;
14 | last_index -= 1;
15 | }
16 | if first_index >= last_index {
17 | return word.to_string();
18 | }
19 |
20 | }
21 | "".to_string()
22 | }
23 |
24 | #[allow(unused)]
25 | fn main() {
26 | let words: Vec = vec!["abc".to_string(),"car".to_string(),"ada".to_string(),"racecar".to_string(),"cool".to_string()];
27 | let words: Vec = vec!["xngla".to_string(),"e".to_string(),"itrn".to_string(),"y".to_string(),"s".to_string(),"pfp".to_string(),"rfd".to_string()];
28 | let res: String = first_palindrome(words);
29 | println!("ans => {res}");
30 | }
--------------------------------------------------------------------------------
/find-polygon-with-largest-perimeter/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "find-polygon-with-largest-perimeter"
3 | version = "0.1.0"
4 | edition = "2021"
5 |
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 |
8 | [dependencies]
9 |
--------------------------------------------------------------------------------
/find-polygon-with-largest-perimeter/desc.txt:
--------------------------------------------------------------------------------
1 | You are given an array of positive integers nums of length n.
2 |
3 | A polygon is a closed plane figure that has at least 3 sides. The longest side of a polygon is smaller than the sum of its other sides.
4 |
5 | Conversely, if you have k (k >= 3) positive real numbers a1, a2, a3, ..., ak where a1 <= a2 <= a3 <= ... <= ak and a1 + a2 + a3 + ... + ak-1 > ak, then there always exists a polygon with k sides whose lengths are a1, a2, a3, ..., ak.
6 |
7 | The perimeter of a polygon is the sum of lengths of its sides.
8 |
9 | Return the largest possible perimeter of a polygon whose sides can be formed from nums, or -1 if it is not possible to create a polygon.
10 |
11 |
12 |
13 | Example 1:
14 |
15 | Input: nums = [5,5,5]
16 | Output: 15
17 | Explanation: The only possible polygon that can be made from nums has 3 sides: 5, 5, and 5. The perimeter is 5 + 5 + 5 = 15.
18 |
19 | Example 2:
20 |
21 | Input: nums = [1,12,1,2,5,50,3]
22 | Output: 12
23 | Explanation: The polygon with the largest perimeter which can be made from nums has 5 sides: 1, 1, 2, 3, and 5. The perimeter is 1 + 1 + 2 + 3 + 5 = 12.
24 | We cannot have a polygon with either 12 or 50 as the longest side because it is not possible to include 2 or more smaller sides that have a greater sum than either of them.
25 | It can be shown that the largest possible perimeter is 12.
26 |
27 | Example 3:
28 |
29 | Input: nums = [5,5,50]
30 | Output: -1
31 | Explanation: There is no possible way to form a polygon from nums, as a polygon has at least 3 sides and 50 > 5 + 5.
32 |
33 |
--------------------------------------------------------------------------------
/find-polygon-with-largest-perimeter/src/main.rs:
--------------------------------------------------------------------------------
1 |
2 | #[allow(unused)]
3 | fn main () {
4 | let nums: Vec = vec![1,12,1,2,5,50,3];
5 | // let nums: Vec = vec![5,5,5];
6 | // let nums: Vec = vec![5,5,50];
7 | let res = largest_perimeter(nums);
8 | println!("{}", res);
9 | }
10 |
11 |
12 | #[allow(unused)]
13 | pub fn largest_perimeter(mut nums: Vec) -> i64 {
14 | let mut nums = nums;
15 | let n = nums.len();
16 | nums.sort_unstable();
17 |
18 | let mut max_sum = -1;
19 | let mut sum = nums[0] as i64;
20 | for i in 1..n {
21 | let num = nums[i] as i64;
22 | if sum > num {
23 | max_sum = max_sum.max(sum + num);
24 | }
25 | sum += num;
26 | }
27 | max_sum
28 | }
29 |
30 |
31 |
32 |
--------------------------------------------------------------------------------
/furtherest-building-you-can-reach/Cargo.lock:
--------------------------------------------------------------------------------
1 | # This file is automatically @generated by Cargo.
2 | # It is not intended for manual editing.
3 | version = 3
4 |
5 | [[package]]
6 | name = "furtherest-building-you-can-reach"
7 | version = "0.1.0"
8 |
--------------------------------------------------------------------------------
/furtherest-building-you-can-reach/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "furtherest-building-you-can-reach"
3 | version = "0.1.0"
4 | edition = "2021"
5 |
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 |
8 | [dependencies]
9 |
--------------------------------------------------------------------------------
/furtherest-building-you-can-reach/desc.txt:
--------------------------------------------------------------------------------
1 | You are given an integer array heights representing the heights of buildings, some bricks, and some ladders.
2 |
3 | You start your journey from building 0 and move to the next building by possibly using bricks or ladders.
4 |
5 | While moving from building i to building i+1 (0-indexed),
6 |
7 | If the current building's height is greater than or equal to the next building's height, you do not need a ladder or bricks.
8 | If the current building's height is less than the next building's height, you can either use one ladder or (h[i+1] - h[i]) bricks.
9 | Return the furthest building index (0-indexed) you can reach if you use the given ladders and bricks optimally.
10 |
11 |
12 |
13 | Example 1:
14 |
15 |
16 | Input: heights = [4,2,7,6,9,14,12], bricks = 5, ladders = 1
17 | Output: 4
18 | Explanation: Starting at building 0, you can follow these steps:
19 | - Go to building 1 without using ladders nor bricks since 4 >= 2.
20 | - Go to building 2 using 5 bricks. You must use either bricks or ladders because 2 < 7.
21 | - Go to building 3 without using ladders nor bricks since 7 >= 6.
22 | - Go to building 4 using your only ladder. You must use either bricks or ladders because 6 < 9.
23 | It is impossible to go beyond building 4 because you do not have any more bricks or ladders.
24 | Example 2:
25 |
26 | Input: heights = [4,12,2,7,3,18,20,3,19], bricks = 10, ladders = 2
27 | Output: 7
28 | Example 3:
29 |
30 | Input: heights = [14,3,19,3], bricks = 17, ladders = 0
31 | Output: 3
32 |
33 |
34 | Constraints:
35 |
36 | 1 <= heights.length <= 105
37 | 1 <= heights[i] <= 106
38 | 0 <= bricks <= 109
39 | 0 <= ladders <= heights.length
--------------------------------------------------------------------------------
/furtherest-building-you-can-reach/src/main.rs:
--------------------------------------------------------------------------------
1 | use std::collections::BinaryHeap;
2 |
3 | #[allow(unused)]
4 | fn main() {
5 | // let heights: Vec = vec![4,12,2,7,3,18,20,3,19];
6 | // let bricks: i32 = 10;
7 | // let ladders: i32 = 2;
8 | // let answer: i32 = furthest_building_1(heights, bricks, ladders);
9 | // println!("case 1 => {}", answer);
10 |
11 | // // heights = [14,3,19,3], bricks = 17, ladders = 0
12 | // let heights: Vec = vec![14,3,19,3];
13 | // let bricks: i32 = 17;
14 | // let ladders: i32 = 0;
15 | // let answer: i32 = furthest_building(heights, bricks, ladders);
16 |
17 | // println!("case 2 => {}", answer);
18 |
19 | let heights: Vec = vec![1,5,1,2,3,4,10000];
20 | let bricks: i32 = 4;
21 | let ladders: i32 = 1;
22 | // let answer: i32 = furthest_building(heights.clone(), bricks.clone(), ladders.clone());
23 | // println!("case 3 => {}", answer);
24 | let answer: i32 = furthest_building_3(heights.clone(), bricks.clone(), ladders.clone());
25 |
26 | println!("case 3 => {}", answer);
27 |
28 |
29 | }
30 |
31 | #[allow(unused)]
32 | pub fn furthest_building(heights: Vec, bricks: i32, ladders: i32) -> i32 {
33 | let mut ladders = ladders;
34 | let mut bricks = bricks;
35 |
36 | let mut index: i32 = 0 ;
37 | let mut jump: i32=0;
38 | let total_buildings = heights.len() as i32;
39 | while index < total_buildings-1{
40 | let mut current_building = heights[index as usize];
41 | let mut next_building = heights[(index + 1) as usize];
42 | println!("current {}, next {}",current_building, next_building);
43 | if current_building >= next_building {
44 | println!("Parkour !!!");
45 | jump += 1;
46 | } else {
47 | let mut diff = next_building - current_building;
48 |
49 | if bricks >= diff {
50 | println!("BRICKS !!!");
51 | bricks -= diff;
52 | jump += 1;
53 | } else if (diff > bricks) && (ladders > 0){
54 | println!("Ladders !!!");
55 | ladders -= 1;
56 | jump += 1;
57 | } else {
58 | break;
59 | }
60 | }
61 | index += 1;
62 | }
63 | // println!("The jump is {}", jump);
64 | jump
65 | }
66 |
67 | #[allow(unused)]
68 | pub fn furthest_building_1(heights: Vec, mut bricks: i32, mut ladders: i32) -> i32 {
69 | let mut jumps = vec![];
70 | let total_buildings = heights.len() as i32;
71 | let mut index: i32 = 0 ;
72 | while index < total_buildings-1{
73 | let current_building = heights[index as usize];
74 | let next_building = heights[(index + 1) as usize];
75 | println!("current {}, next {}",current_building, next_building);
76 | if current_building < next_building {
77 | let diff = next_building - current_building;
78 | println!("diff => {:?}", diff);
79 | println!("Jumps initial => {:?}", jumps);
80 | jumps.push(diff);
81 | println!("Jumps added => {:?}", jumps);
82 | jumps.sort();
83 | println!("Jumps sorted => {:?}", jumps);
84 | println!("ladders initial => {}", ladders);
85 | if jumps.len() > ladders as usize {
86 | println!("Jumps => {:?}", jumps);
87 | println!("bricks => {:?}", bricks);
88 | bricks -= jumps[0];
89 | println!("bricks => {:?}", bricks);
90 | jumps.remove(0);
91 | println!("Jumps => {:?}", jumps);
92 | }
93 | println!("ladders final => {}", ladders);
94 | if bricks < 0 {
95 | return index;
96 | }
97 | }
98 | println!("PARKOUR");
99 | index += 1;
100 | }
101 | index
102 | }
103 |
104 |
105 | #[allow(unused)]
106 | pub fn furthest_building_2(heights: Vec, mut bricks: i32, mut ladders: i32) -> i32 {
107 | let mut jumps = vec![];
108 | let total_buildings = heights.len() as i32;
109 | let mut index: i32 = 0 ;
110 | while index < total_buildings-1{
111 | let current_building = heights[index as usize];
112 | let next_building = heights[(index + 1) as usize];
113 | if current_building < next_building {
114 | let diff = next_building - current_building;
115 | jumps.push(diff);
116 | jumps.sort();
117 | if ladders > 0 {
118 | ladders -= 1;
119 | } else if !jumps.is_empty() {
120 | bricks -= jumps[0];
121 | jumps.remove(0);
122 | }
123 | if bricks < 0 {
124 | return index;
125 | }
126 | }
127 | index += 1;
128 | }
129 | index
130 | }
131 |
132 |
133 | #[allow(unused)]
134 | pub fn furthest_building_3(heights: Vec, bricks: i32, ladders: i32) -> i32 {
135 | let mut bricks = bricks;
136 | let mut ladders = ladders;
137 |
138 | let mut difference: BinaryHeap = BinaryHeap::new();
139 |
140 | let length = heights.len();
141 |
142 | for i in 0..(length -1){
143 | let diff = heights[i+1] - heights[i] ;
144 | if diff <= 0{
145 | continue;
146 | }
147 |
148 | difference.push(diff);
149 |
150 | bricks -= diff;
151 | if bricks < 0 && ladders > 0 {
152 | bricks += difference.pop().unwrap();
153 | ladders -= 1;
154 | }
155 | if bricks < 0 {
156 | return i as i32;
157 | }
158 | }
159 |
160 | (length-1) as i32
161 | }
--------------------------------------------------------------------------------
/group-anagrams/Cargo.lock:
--------------------------------------------------------------------------------
1 | # This file is automatically @generated by Cargo.
2 | # It is not intended for manual editing.
3 | version = 3
4 |
5 | [[package]]
6 | name = "group-anagrams"
7 | version = "0.1.0"
8 |
--------------------------------------------------------------------------------
/group-anagrams/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "group-anagrams"
3 | version = "0.1.0"
4 | edition = "2021"
5 |
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 |
8 | [dependencies]
9 |
--------------------------------------------------------------------------------
/group-anagrams/desc.txt:
--------------------------------------------------------------------------------
1 | Given an array of strings strs, group the anagrams together. You can return the answer in any order.
2 |
3 | An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
4 |
5 |
6 |
7 | Example 1:
8 |
9 | Input: strs = ["eat","tea","tan","ate","nat","bat"]
10 | Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
11 |
12 | Example 2:
13 |
14 | Input: strs = [""]
15 | Output: [[""]]
16 |
17 | Example 3:
18 |
19 | Input: strs = ["a"]
20 | Output: [["a"]]
21 |
22 |
--------------------------------------------------------------------------------
/group-anagrams/src/main.rs:
--------------------------------------------------------------------------------
1 | use std::collections::HashMap;
2 |
3 | fn main() {
4 | let strs = vec!["eat".to_string(),"tea".to_string(),"tan".to_string(),"ate".to_string(),"nat".to_string(),"bat".to_string()];
5 |
6 | println!("{:?}", group_anagrams(strs));
7 | }
8 |
9 |
10 | pub fn group_anagrams(strs: Vec) -> Vec> {
11 | let mut hmap: HashMap> = HashMap::new();
12 |
13 | let original = strs.clone();
14 |
15 | let mut sorted: Vec = Vec::new();
16 |
17 | for i in 0..original.len(){
18 | let mut temp: Vec = original[i].clone().chars().collect();
19 | // println!("{:?}", temp);
20 | temp.sort_unstable();
21 | let temp: String = temp.into_iter().collect();
22 | // println!("{:?}", temp);
23 | sorted.push(temp);
24 | }
25 |
26 | // println!("{:?}", sorted);
27 | // println!("MAP => {:?}", hmap);
28 | for (index, item) in sorted.iter().enumerate(){
29 | // println!("{:?}", item);
30 |
31 | if let Some(val) = hmap.get_mut(item) {
32 | val.push(original[index].clone());
33 | } else {
34 | // map.insert(item, vec![original[index].clone()]);
35 | hmap.insert(item.clone(), vec![original[index].clone()]);
36 | }
37 | }
38 |
39 | let output: Vec> = hmap.into_iter().map(|(_, v)| v).collect();
40 |
41 |
42 | output
43 |
44 | // todo!()
45 | }
--------------------------------------------------------------------------------
/least-number-of-integers-after-k-removals/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "least-number-of-integers-after-k-removals"
3 | version = "0.1.0"
4 | edition = "2021"
5 |
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 |
8 | [dependencies]
9 |
--------------------------------------------------------------------------------
/least-number-of-integers-after-k-removals/desc.txt:
--------------------------------------------------------------------------------
1 | Given an array of integers arr and an integer k. Find the least number of unique integers after removing exactly k elements.
2 |
3 |
4 |
5 | Example 1:
6 |
7 | Input: arr = [5,5,4], k = 1
8 | Output: 1
9 | Explanation: Remove the single 4, only 5 is left.
10 |
11 | Example 2:
12 |
13 | Input: arr = [4,3,1,1,3,3,2], k = 3
14 | Output: 2
15 | Explanation: Remove 4, 2 and either one of the two 1s or three 3s. 1 and 3 will be left.
16 |
17 |
18 |
19 | Constraints:
20 |
21 | 1 <= arr.length <= 10^5
22 | 1 <= arr[i] <= 10^9
23 | 0 <= k <= arr.length
24 |
--------------------------------------------------------------------------------
/least-number-of-integers-after-k-removals/src/main.rs:
--------------------------------------------------------------------------------
1 | use std::collections::HashMap;
2 | #[allow(unused)]
3 | fn main () {
4 | let nums: Vec= vec![4,3,1,1,3,3,2];
5 | let k: i32 = 3;
6 | let nums: Vec= vec![5,5,4];
7 | let k = 1;
8 | let res = find_least_num_of_unique_ints(nums, k);
9 | }
10 |
11 | #[allow(unused)]
12 | pub fn find_least_num_of_unique_ints(arr: Vec, k: i32) -> i32 {
13 | let dup_arr: Vec = arr;
14 | let length = dup_arr.len();
15 | let mut count_pointer : HashMap = HashMap::new();
16 | let mut i=0;
17 | while i < length{
18 | if let Some(value) = count_pointer.get_mut(&dup_arr[i]) {
19 | *value += 1;
20 | } else {
21 | count_pointer.insert(dup_arr[i], 1);
22 | }
23 | i+=1;
24 | }
25 | let mut values: Vec = count_pointer.values().cloned().collect();
26 | println!("{:?}", values);
27 | values.sort();
28 | println!("{:?}", values);
29 | let result = consume_vector(values.clone(), k);
30 | println!("{:?}", result);
31 |
32 | let mut count: i32 = 0;
33 | for item in result{
34 | if item != 0 {
35 | count +=1;
36 | }
37 | }
38 | println!("{:?}", count);
39 | count
40 | // todo!()
41 | }
42 |
43 | #[allow(unused)]
44 | fn consume_vector(mut vec: Vec, num: i32) -> Vec {
45 | let mut sum = 0;
46 | for i in 0..vec.len() {
47 | if sum + vec[i] <= num {
48 | sum += vec[i];
49 | vec[i] = 0;
50 | } else if sum + vec[i] > num && sum < num {
51 | let diff = num - sum;
52 | vec[i] -= diff;
53 | sum += diff;
54 | }
55 | if sum >= num {
56 | break;
57 | }
58 | }
59 | vec
60 | }
--------------------------------------------------------------------------------
/longest-common-prefix/Cargo.lock:
--------------------------------------------------------------------------------
1 | # This file is automatically @generated by Cargo.
2 | # It is not intended for manual editing.
3 | version = 3
4 |
5 | [[package]]
6 | name = "longest-common-prefix"
7 | version = "0.1.0"
8 |
--------------------------------------------------------------------------------
/longest-common-prefix/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "longest-common-prefix"
3 | version = "0.1.0"
4 | edition = "2021"
5 |
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 |
8 | [dependencies]
9 |
--------------------------------------------------------------------------------
/longest-common-prefix/desc.txt:
--------------------------------------------------------------------------------
1 | Write a function to find the longest common prefix string amongst an array of strings.
2 |
3 | If there is no common prefix, return an empty string "".
4 |
5 |
6 |
7 | Example 1:
8 |
9 | Input: strs = ["flower","flow","flight"]
10 | Output: "fl"
11 |
12 | Example 2:
13 |
14 | Input: strs = ["dog","racecar","car"]
15 | Output: ""
16 | Explanation: There is no common prefix among the input strings.
17 |
18 |
--------------------------------------------------------------------------------
/longest-common-prefix/src/main.rs:
--------------------------------------------------------------------------------
1 | fn main() {
2 | println!("Hello, world!");
3 |
4 | let strs = vec!["flower".to_string(), "flow".to_string(), "flight".to_string()];
5 | let longest = longest_common_prefix(strs);
6 | println!("{}", longest);
7 |
8 | let strs = vec!["dog".to_string(), "racecar".to_string(), "car".to_string()];
9 | let longest = longest_common_prefix(strs);
10 | println!("{}", longest);
11 |
12 | }
13 |
14 | pub fn longest_common_prefix(strs: Vec) -> String {
15 | if strs.is_empty() {
16 | return "".to_string();
17 | }
18 |
19 | let mut common = strs[0].clone();
20 |
21 | for s in &strs[1..] {
22 | while !s.starts_with(&common) {
23 | common.pop();
24 | if common.is_empty() {
25 | return common;
26 | }
27 | }
28 | }
29 |
30 | common
31 | }
32 |
--------------------------------------------------------------------------------
/majority-element/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "majority-element"
3 | version = "0.1.0"
4 | edition = "2021"
5 |
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 |
8 | [dependencies]
9 |
--------------------------------------------------------------------------------
/majority-element/desc.txt:
--------------------------------------------------------------------------------
1 | 169. Majority Element
2 | Solved
3 | Easy
4 | Topics
5 | Companies
6 |
7 | Given an array nums of size n, return the majority element.
8 |
9 | The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists in the array.
10 |
11 |
12 |
13 | Example 1:
14 |
15 | Input: nums = [3,2,3]
16 | Output: 3
17 |
18 | Example 2:
19 |
20 | Input: nums = [2,2,1,1,1,2,2]
21 | Output: 2
22 |
23 |
24 |
25 | Constraints:
26 |
27 | n == nums.length
28 | 1 <= n <= 5 * 104
29 | -109 <= nums[i] <= 109
30 |
--------------------------------------------------------------------------------
/majority-element/src/main.rs:
--------------------------------------------------------------------------------
1 | use std::collections::HashMap;
2 |
3 | #[allow(unused)]
4 | pub fn majority_element_alternative(nums: Vec) -> i32 {
5 | let mut store: HashMap = HashMap::new();
6 | for item in nums.iter(){
7 | if let Some(value) = store.get_mut(item) {
8 | *value += 1;
9 | if *value > ( nums.len() as i32 )/2{
10 | return *item as i32;
11 | }
12 | } else {
13 | store.insert(*item, 1);
14 | }
15 | }
16 | let mut max_val = std::i32::MIN;
17 | let mut last_count: i32 = 0;
18 | for (key, val) in store.into_iter() {
19 | if last_count < val {
20 | max_val = key;
21 | // println!("{} {}", key, val);
22 | }
23 | }
24 | max_val
25 | }
26 |
27 | #[allow(unused)]
28 | pub fn majority_element(nums: Vec) -> i32 {
29 | let mut store: HashMap = HashMap::new();
30 | for item in nums.iter(){
31 | if let Some(value) = store.get_mut(item) {
32 | *value += 1;
33 | if *value > ( nums.len() as i32 )/2{
34 | return *item as i32;
35 | }
36 | } else {
37 | store.insert(*item, 1);
38 | }
39 | }
40 | let mut max_val: i32 = std::i32::MIN;
41 | if let Some((&key, _)) = store.iter().max_by_key(|&(_, val)| val) {
42 | max_val = key;
43 | }
44 | max_val
45 | }
46 |
47 | #[allow(unused)]
48 | fn main() {
49 | let nums: Vec = vec![2,2,1,1,1,2,2];
50 | let res = majority_element(nums);
51 | println!("{}", res);
52 | }
--------------------------------------------------------------------------------
/meeting-rooms-III/desc.txt:
--------------------------------------------------------------------------------
1 | You are given an integer n. There are n rooms numbered from 0 to n - 1.
2 |
3 | You are given a 2D integer array meetings where meetings[i] = [starti, endi] means that a meeting will be held during the half-closed time interval [starti, endi). All the values of starti are unique.
4 |
5 | Meetings are allocated to rooms in the following manner:
6 |
7 | Each meeting will take place in the unused room with the lowest number.
8 | If there are no available rooms, the meeting will be delayed until a room becomes free. The delayed meeting should have the same duration as the original meeting.
9 | When a room becomes unused, meetings that have an earlier original start time should be given the room.
10 | Return the number of the room that held the most meetings. If there are multiple rooms, return the room with the lowest number.
11 |
12 | A half-closed interval [a, b) is the interval between a and b including a and not including b.
13 |
14 |
15 |
16 | Example 1:
17 |
18 | Input: n = 2, meetings = [[0,10],[1,5],[2,7],[3,4]]
19 | Output: 0
20 | Explanation:
21 | - At time 0, both rooms are not being used. The first meeting starts in room 0.
22 | - At time 1, only room 1 is not being used. The second meeting starts in room 1.
23 | - At time 2, both rooms are being used. The third meeting is delayed.
24 | - At time 3, both rooms are being used. The fourth meeting is delayed.
25 | - At time 5, the meeting in room 1 finishes. The third meeting starts in room 1 for the time period [5,10).
26 | - At time 10, the meetings in both rooms finish. The fourth meeting starts in room 0 for the time period [10,11).
27 | Both rooms 0 and 1 held 2 meetings, so we return 0.
28 | Example 2:
29 |
30 | Input: n = 3, meetings = [[1,20],[2,10],[3,5],[4,9],[6,8]]
31 | Output: 1
32 | Explanation:
33 | - At time 1, all three rooms are not being used. The first meeting starts in room 0.
34 | - At time 2, rooms 1 and 2 are not being used. The second meeting starts in room 1.
35 | - At time 3, only room 2 is not being used. The third meeting starts in room 2.
36 | - At time 4, all three rooms are being used. The fourth meeting is delayed.
37 | - At time 5, the meeting in room 2 finishes. The fourth meeting starts in room 2 for the time period [5,10).
38 | - At time 6, all three rooms are being used. The fifth meeting is delayed.
39 | - At time 10, the meetings in rooms 1 and 2 finish. The fifth meeting starts in room 1 for the time period [10,12).
40 | Room 0 held 1 meeting while rooms 1 and 2 each held 2 meetings, so we return 1.
41 |
42 |
43 | Constraints:
44 |
45 | 1 <= n <= 100
46 | 1 <= meetings.length <= 105
47 | meetings[i].length == 2
48 | 0 <= starti < endi <= 5 * 105
49 | All the values of starti are unique.
--------------------------------------------------------------------------------
/meeting-rooms-III/meeting-room-III-rs/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "meeting-room-III-rs"
3 | version = "0.1.0"
4 | edition = "2021"
5 |
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 |
8 | [dependencies]
9 |
--------------------------------------------------------------------------------
/meeting-rooms-III/meeting-room-III-rs/src/main.rs:
--------------------------------------------------------------------------------
1 | #[allow(unused)]
2 | use std::collections::BinaryHeap;
3 | use std::cmp::Reverse;
4 |
5 |
6 | #[allow(unused)]
7 | fn main() {
8 | let n: i32 = 2;
9 | let meetings: Vec> = vec![[0,10].to_vec(),[1,5].to_vec(),[2,7].to_vec(),[3,4].to_vec()];
10 | let answer = most_booked(n, meetings);
11 | println!("Answer => {answer}");
12 |
13 | let n = 3_i32;
14 | let meetings: Vec> = vec![vec![1,20],vec![2,10],vec![3,5],vec![4,9],vec![6,8]];
15 | let answer = most_booked(n, meetings);
16 | println!("Answer => {answer}");
17 | }
18 |
19 | #[allow(unused)]
20 | pub fn most_booked(n: i32, meetings: Vec>) -> i32 {
21 | let mut meetings = meetings;
22 | meetings.sort_unstable();
23 |
24 | let mut freq = vec![0; n as usize];
25 |
26 | let mut available: BinaryHeap> = (0..n as usize).map(Reverse).collect();
27 | let mut booked: BinaryHeap> = BinaryHeap::new();
28 |
29 | for arr in meetings {
30 | let (start, end) = (arr[0], arr[1]);
31 | while !booked.is_empty()
32 | && booked.peek().map(|&Reverse((s, _))| s).unwrap() <= start as i64
33 | {
34 | let Reverse((_, room)) = booked.pop().unwrap();
35 | available.push(Reverse(room));
36 | }
37 | if let Some(Reverse(room)) = available.pop() {
38 | booked.push(Reverse((end as i64, room)));
39 | freq[room] += 1;
40 | } else if let Some(Reverse((free, room))) = booked.pop() {
41 | booked.push(Reverse((free + (end - start) as i64, room)));
42 | freq[room] += 1;
43 | }
44 | }
45 |
46 | freq.into_iter()
47 | .zip(0..)
48 | .max_by_key(|&(count, room)| (count, -room))
49 | .map(|(_, room)| room)
50 | .unwrap()
51 | }
52 |
53 |
--------------------------------------------------------------------------------
/meeting-rooms-III/py-solution/main.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def mostBooked(self, n: int, meetings: List[List[int]]) -> int:
3 | meetings.sort()
4 |
5 | available = [i for i in range(n)] # 0, 1, 2, 3..
6 | used = [] # (end_time, room_number)
7 | count = [0] * n # count[n] = eetings scheduled
8 |
9 | for start, end in meetings:
10 | # Finish meetings
11 | while used and start >= used[0][0]:
12 | _, room = heapq.heappop(used)
13 | heapq.heappush(available, room)
14 |
15 | # no room is available
16 | if not available:
17 | end_time, room = heapq.heappop(used)
18 | end = end_time + (end - start)
19 | heapq.heappush(available, room)
20 |
21 | # a room is available
22 | room = heapq.heappop(available)
23 | heapq.heappush(used, (end, room))
24 | count[room] += 1
25 |
26 | return count.index(max(count))
--------------------------------------------------------------------------------
/missing-number/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "missing-number"
3 | version = "0.1.0"
4 | edition = "2021"
5 |
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 |
8 | [dependencies]
9 |
--------------------------------------------------------------------------------
/missing-number/desc.txt:
--------------------------------------------------------------------------------
1 | Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array.
2 |
3 |
4 |
5 | Example 1:
6 |
7 | Input: nums = [3,0,1]
8 | Output: 2
9 | Explanation: n = 3 since there are 3 numbers, so all numbers are in the range [0,3]. 2 is the missing number in the range since it does not appear in nums.
10 |
11 | Example 2:
12 |
13 | Input: nums = [0,1]
14 | Output: 2
15 | Explanation: n = 2 since there are 2 numbers, so all numbers are in the range [0,2]. 2 is the missing number in the range since it does not appear in nums.
16 |
17 | Example 3:
18 |
19 | Input: nums = [9,6,4,2,3,5,7,0,1]
20 | Output: 8
21 | Explanation: n = 9 since there are 9 numbers, so all numbers are in the range [0,9]. 8 is the missing number in the range since it does not appear in nums.
22 |
23 |
24 |
25 | Constraints:
26 |
27 | n == nums.length
28 | 1 <= n <= 104
29 | 0 <= nums[i] <= n
30 | All the numbers of nums are unique.
31 |
32 | git pull
33 |
--------------------------------------------------------------------------------
/missing-number/src/main.rs:
--------------------------------------------------------------------------------
1 |
2 | #[allow(unused)]
3 | fn main () {
4 | let nums: Vec = vec![3,0,1];
5 | println!("Missing Number {}", missing_number(nums));
6 |
7 | let nums: Vec = vec![1];
8 | println!("Missing Number {}", missing_number(nums));
9 |
10 | let nums: Vec = vec![1,2];
11 | println!("Missing Number {}", missing_number(nums));
12 | }
13 |
14 |
15 | #[allow(unused)]
16 | pub fn missing_number(mut nums: Vec) -> i32 {
17 | nums.sort_unstable();
18 |
19 | let end = nums[nums.len()-1];
20 | let mut index = 0;
21 |
22 | let mut missing: Option = None ;
23 |
24 | while index < nums.len() {
25 | // println!("Pointer => {}, current => {}", pointer, nums[index]);
26 | if nums[index] != index as i32 {
27 |
28 | missing = Some(index as i32);
29 | break;
30 | }
31 | index += 1;
32 | }
33 | match missing {
34 | Some(value) => value,
35 | None => nums[nums.len()-1] +1
36 | }
37 | }
38 |
39 |
40 |
--------------------------------------------------------------------------------
/palindrome-number/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "palindrome-number"
3 | version = "0.1.0"
4 | edition = "2021"
5 |
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 |
8 | [dependencies]
9 |
--------------------------------------------------------------------------------
/palindrome-number/desc.txt:
--------------------------------------------------------------------------------
1 | 9. Palindrome Number
2 |
3 | Given an integer x, return true if x is a
4 | palindrome
5 | , and false otherwise.
6 |
7 |
8 |
9 | Example 1:
10 |
11 | Input: x = 121
12 | Output: true
13 | Explanation: 121 reads as 121 from left to right and from right to left.
14 |
15 | Example 2:
16 |
17 | Input: x = -121
18 | Output: false
19 | Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
20 |
21 | Example 3:
22 |
23 | Input: x = 10
24 | Output: false
25 | Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
26 |
27 |
28 |
29 | Constraints:
30 |
31 | -231 <= x <= 231 - 1
32 |
33 |
--------------------------------------------------------------------------------
/palindrome-number/src/main.rs:
--------------------------------------------------------------------------------
1 | fn main() {
2 | println!("{}", is_palindrome(121_i32) );
3 | println!("{}", is_palindrome(1121_i32) );
4 | }
5 |
6 |
7 | pub fn is_palindrome(x: i32) -> bool {
8 | let num_str: Vec = x.to_string().chars().collect();
9 |
10 | let mut last_ind = num_str.len() -1;
11 | for (index, ch) in num_str.iter().enumerate() {
12 |
13 | if num_str[index] != num_str[last_ind] {
14 | return false;
15 | }
16 | last_ind -= 1;
17 | }
18 |
19 | true
20 | }
--------------------------------------------------------------------------------
/perfect-squares-idk/Cargo.lock:
--------------------------------------------------------------------------------
1 | # This file is automatically @generated by Cargo.
2 | # It is not intended for manual editing.
3 | version = 3
4 |
5 | [[package]]
6 | name = "perfect-squares-idk"
7 | version = "0.1.0"
8 |
--------------------------------------------------------------------------------
/perfect-squares-idk/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "perfect-squares-idk"
3 | version = "0.1.0"
4 | edition = "2021"
5 |
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 |
8 | [dependencies]
9 |
--------------------------------------------------------------------------------
/perfect-squares-idk/desc.txt:
--------------------------------------------------------------------------------
1 | Given an integer n, return the least number of perfect square numbers that sum to n.
2 |
3 | A perfect square is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, 1, 4, 9, and 16 are perfect squares while 3 and 11 are not.
4 |
5 |
6 |
7 | Example 1:
8 |
9 | Input: n = 12
10 | Output: 3
11 | Explanation: 12 = 4 + 4 + 4.
12 |
13 | Example 2:
14 |
15 | Input: n = 13
16 | Output: 2
17 | Explanation: 13 = 4 + 9.
18 |
19 |
--------------------------------------------------------------------------------
/perfect-squares-idk/src/main.rs:
--------------------------------------------------------------------------------
1 | fn num_squares(n: i32) -> i32 {
2 | // Create an array to store the minimum number of perfect squares required
3 | // to sum up to each number from 0 to n
4 | let mut dp = vec![i32::MAX; (n + 1) as usize];
5 |
6 | // Base case: 0 requires 0 perfect squares
7 | dp[0] = 0;
8 |
9 | // Iterate from 1 to n
10 | for i in 1..=n {
11 | // Iterate through all possible perfect squares less than or equal to i
12 | for j in 1..=((i as f64).sqrt() as i32) {
13 | // Update dp[i] with the minimum of its current value and 1 (perfect square j*j) plus dp[i - j*j]
14 | dp[i as usize] = dp[i as usize].min(1 + dp[(i - j*j) as usize]);
15 | }
16 | }
17 |
18 | // The result is stored in dp[n]
19 | dp[n as usize]
20 | }
21 |
22 | fn main() {
23 | // Example usage:
24 | let n = 12;
25 |
26 | println!("Minimum number of perfect squares required to sum up to {}: {}", n, num_squares(n));
27 | // let mut dp = vec![i32::MAX; (n + 1) as usize];
28 | // println!("{:?}", dp);
29 | }
30 |
--------------------------------------------------------------------------------
/power-of-two/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "power-of-two"
3 | version = "0.1.0"
4 | edition = "2021"
5 |
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 |
8 | [dependencies]
9 |
--------------------------------------------------------------------------------
/power-of-two/desc.txt:
--------------------------------------------------------------------------------
1 | Given an integer n, return true if it is a power of two. Otherwise, return false.
2 |
3 | An integer n is a power of two, if there exists an integer x such that n == 2x.
4 |
5 |
6 |
7 | Example 1:
8 |
9 | Input: n = 1
10 | Output: true
11 | Explanation: 20 = 1
12 |
13 | Example 2:
14 |
15 | Input: n = 16
16 | Output: true
17 | Explanation: 24 = 16
18 |
19 | Example 3:
20 |
21 | Input: n = 3
22 | Output: false
23 |
24 |
25 |
26 | Constraints:
27 |
28 | -231 <= n <= 231 - 1
29 |
30 |
--------------------------------------------------------------------------------
/power-of-two/src/main.rs:
--------------------------------------------------------------------------------
1 |
2 | #[allow(unused)]
3 | fn main () {
4 | let n = 8_i32;
5 | // let res = is_power_of_two(n);
6 | let res = n & (n-1);
7 | println!("is it =>{}", res);
8 | let n = 0_i32;
9 | let res = is_power_of_two(n);
10 | println!("is it =>{}", res);
11 | let n = 3_i32;
12 | let res = is_power_of_two(n);
13 | println!("is it =>{}", res);
14 | let n = 2097151_i32;
15 | let res = is_power_of_two(n);
16 | println!("is it =>{}", res);
17 | }
18 |
19 |
20 | #[allow(unused)]
21 | pub fn is_power_of_two(n: i32) -> bool {
22 | n > 0 && n & (n-1) == 0
23 | }
24 |
25 |
26 |
27 |
--------------------------------------------------------------------------------
/rearrange-array-element-by-sign/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "rearrange-array-element-by-sign"
3 | version = "0.1.0"
4 | edition = "2021"
5 |
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 |
8 | [dependencies]
9 |
--------------------------------------------------------------------------------
/rearrange-array-element-by-sign/desc.txt:
--------------------------------------------------------------------------------
1 | You are given a 0-indexed integer array nums of even length consisting of an equal number of positive and negative integers.
2 |
3 | You should rearrange the elements of nums such that the modified array follows the given conditions:
4 |
5 | Every consecutive pair of integers have opposite signs.
6 | For all integers with the same sign, the order in which they were present in nums is preserved.
7 | The rearranged array begins with a positive integer.
8 |
9 | Return the modified array after rearranging the elements to satisfy the aforementioned conditions.
10 |
11 |
12 |
13 | Example 1:
14 |
15 | Input: nums = [3,1,-2,-5,2,-4]
16 | Output: [3,-2,1,-5,2,-4]
17 | Explanation:
18 | The positive integers in nums are [3,1,2]. The negative integers are [-2,-5,-4].
19 | The only possible way to rearrange them such that they satisfy all conditions is [3,-2,1,-5,2,-4].
20 | Other ways such as [1,-2,2,-5,3,-4], [3,1,2,-2,-5,-4], [-2,3,-5,1,-4,2] are incorrect because they do not satisfy one or more conditions.
21 |
22 | Example 2:
23 |
24 | Input: nums = [-1,1]
25 | Output: [1,-1]
26 | Explanation:
27 | 1 is the only positive integer and -1 the only negative integer in nums.
28 | So nums is rearranged to [1,-1].
29 |
--------------------------------------------------------------------------------
/rearrange-array-element-by-sign/src/main.rs:
--------------------------------------------------------------------------------
1 | #[allow(unused)]
2 | pub fn rearrange_array(nums: Vec) -> Vec {
3 | let mut positive: Vec = vec![];
4 | let mut negative: Vec = vec![];
5 | let mut result: Vec = vec![];
6 |
7 | for item in nums.iter() {
8 | if *item < 0_i32 {
9 | negative.push(*item);
10 | } else {
11 | positive.push(*item);
12 | }
13 | }
14 |
15 | let mut i=0;
16 | let length cargo ();
17 | while i< length {
18 | result.push(positive[i]);
19 | result.push(negative[i]);
20 | i += 1;
21 | }
22 | result
23 | }
24 |
25 | #[allow(unused)]
26 | fn main() {
27 | let nums: Vec = vec![3,1,-2,-5,2,-4];
28 | let res = rearrange_array(nums);
29 | println!("{:?}", res);
30 |
31 | let nums: Vec = vec![-1,1];
32 | let res = rearrange_array(nums);
33 | println!("{:?}", res);
34 | }
--------------------------------------------------------------------------------
/remove-duplicate-from-sorted-arrays/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "remove-duplicate-from-sorted-arrays"
3 | version = "0.1.0"
4 | edition = "2021"
5 |
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 |
8 | [dependencies]
9 |
--------------------------------------------------------------------------------
/remove-duplicate-from-sorted-arrays/desc.txt:
--------------------------------------------------------------------------------
1 | Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Then return the number of unique elements in nums.
2 |
3 | Consider the number of unique elements of nums to be k, to get accepted, you need to do the following things:
4 |
5 | Change the array nums such that the first k elements of nums contain the unique elements in the order they were present in nums initially. The remaining elements of nums are not important as well as the size of nums.
6 | Return k.
7 |
8 | Custom Judge:
9 |
10 | The judge will test your solution with the following code:
11 |
12 | int[] nums = [...]; // Input array
13 | int[] expectedNums = [...]; // The expected answer with correct length
14 |
15 | int k = removeDuplicates(nums); // Calls your implementation
16 |
17 | assert k == expectedNums.length;
18 | for (int i = 0; i < k; i++) {
19 | assert nums[i] == expectedNums[i];
20 | }
21 |
22 | If all assertions pass, then your solution will be accepted.
23 |
24 |
25 |
26 | Example 1:
27 |
28 | Input: nums = [1,1,2]
29 | Output: 2, nums = [1,2,_]
30 | Explanation: Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively.
31 | It does not matter what you leave beyond the returned k (hence they are underscores).
32 |
33 | Example 2:
34 |
35 | Input: nums = [0,0,1,1,1,2,2,3,3,4]
36 | Output: 5, nums = [0,1,2,3,4,_,_,_,_,_]
37 | Explanation: Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively.
38 | It does not matter what you leave beyond the returned k (hence they are underscores).
39 |
--------------------------------------------------------------------------------
/remove-duplicate-from-sorted-arrays/src/main.rs:
--------------------------------------------------------------------------------
1 | #[allow(unused)]
2 | fn main () {
3 | let mut data_arr: Vec = vec![1,1,2];
4 | let ans = remove_duplicates(&mut data_arr);
5 | println!("{ans}");
6 | }
7 |
8 | #[allow(unused)]
9 | pub fn remove_duplicates(nums: &mut Vec) -> i32 {
10 |
11 | let mut copy: Vec = vec![];
12 |
13 | for item in nums.iter() {
14 | if !copy.contains(item) {
15 | copy.push(*item);
16 | }
17 | }
18 |
19 | nums.clear();
20 | for item in copy.iter() {
21 | nums.push(*item);
22 | }
23 |
24 | copy.len() as i32
25 | }
--------------------------------------------------------------------------------
/roman-to-integer/Cargo.lock:
--------------------------------------------------------------------------------
1 | # This file is automatically @generated by Cargo.
2 | # It is not intended for manual editing.
3 | version = 3
4 |
5 | [[package]]
6 | name = "roman-to-integer"
7 | version = "0.1.0"
8 |
--------------------------------------------------------------------------------
/roman-to-integer/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "roman-to-integer"
3 | version = "0.1.0"
4 | edition = "2021"
5 |
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 |
8 | [dependencies]
9 |
--------------------------------------------------------------------------------
/roman-to-integer/desc.txt:
--------------------------------------------------------------------------------
1 | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
2 |
3 | Symbol Value
4 | I 1
5 | V 5
6 | X 10
7 | L 50
8 | C 100
9 | D 500
10 | M 1000
11 |
12 | For example, 2 is written as II in Roman numeral, just two ones added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II.
13 |
14 | Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:
15 |
16 | I can be placed before V (5) and X (10) to make 4 and 9.
17 | X can be placed before L (50) and C (100) to make 40 and 90.
18 | C can be placed before D (500) and M (1000) to make 400 and 900.
19 |
20 | Given a roman numeral, convert it to an integer.
21 |
22 |
23 |
24 | Example 1:
25 |
26 | Input: s = "III"
27 | Output: 3
28 | Explanation: III = 3.
29 |
30 | Example 2:
31 |
32 | Input: s = "LVIII"
33 | Output: 58
34 | Explanation: L = 50, V= 5, III = 3.
35 |
36 | Example 3:
37 |
38 | Input: s = "MCMXCIV"
39 | Output: 1994
40 | Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
41 |
42 |
--------------------------------------------------------------------------------
/roman-to-integer/src/main.rs:
--------------------------------------------------------------------------------
1 | use std::collections::HashMap;
2 |
3 |
4 | fn main() {
5 | let s = "III".to_string();
6 | let res = roman_to_int(s);
7 | println!("{}", res);
8 |
9 | let s = "LVIII".to_string();
10 | let res = roman_to_int(s);
11 | println!("{}", res);
12 |
13 | let s = "MCMXCIV".to_string();
14 | let res = roman_to_int(s);
15 | println!("{}", res);
16 |
17 | }
18 |
19 | pub fn roman_to_int(s: String) -> i32 {
20 | let mut result: i32 = 0;
21 | let static_vals: HashMap = [
22 | ("I".to_string(), 1_i32),
23 | ("V".to_string(), 5_i32),
24 | ("X".to_string(), 10_i32),
25 | ("L".to_string(), 50_i32),
26 | ("C".to_string(), 100_i32),
27 | ("D".to_string(), 500_i32),
28 | ("M".to_string(), 1000_i32),
29 | ]
30 | .iter()
31 | .cloned()
32 | .collect();
33 |
34 | // println!("{:?}", static_vals);
35 |
36 | let mut last_char: String = "A".to_string();
37 | for (_i, ch) in s.chars().rev().enumerate() {
38 | let character: String = ch.into();
39 |
40 | let current_value: i32;
41 | if let Some(&value) = static_vals.get(&character) {
42 | current_value = value.clone();
43 | } else {
44 | current_value = 0_i32;
45 | }
46 |
47 | let previous_val: i32;
48 |
49 | if let Some(&value) = static_vals.get(&last_char) {
50 | previous_val = value.clone();
51 | } else {
52 | previous_val = 0_i32;
53 | }
54 |
55 | if previous_val > current_value {
56 | result += -current_value
57 | } else {
58 | result += current_value
59 | }
60 |
61 | // println!("current {character}, previous {last_char}");
62 |
63 | last_char = ch.into();
64 | }
65 |
66 | result
67 | }
68 |
--------------------------------------------------------------------------------
/sort-characters-by-frequency/Cargo.lock:
--------------------------------------------------------------------------------
1 | # This file is automatically @generated by Cargo.
2 | # It is not intended for manual editing.
3 | version = 3
4 |
5 | [[package]]
6 | name = "sort-characters-by-frequency"
7 | version = "0.1.0"
8 |
--------------------------------------------------------------------------------
/sort-characters-by-frequency/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "sort-characters-by-frequency"
3 | version = "0.1.0"
4 | edition = "2021"
5 |
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 |
8 | [dependencies]
9 |
--------------------------------------------------------------------------------
/sort-characters-by-frequency/src/desc.txt:
--------------------------------------------------------------------------------
1 | Given a string s, sort it in decreasing order based on the frequency of the characters. The frequency of a character is the number of times it appears in the string.
2 |
3 | Return the sorted string. If there are multiple answers, return any of them.
4 |
5 |
6 |
7 | Example 1:
8 |
9 | Input: s = "tree"
10 | Output: "eert"
11 | Explanation: 'e' appears twice while 'r' and 't' both appear once.
12 | So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer.
13 |
14 | Example 2:
15 |
16 | Input: s = "cccaaa"
17 | Output: "aaaccc"
18 | Explanation: Both 'c' and 'a' appear three times, so both "cccaaa" and "aaaccc" are valid answers.
19 | Note that "cacaca" is incorrect, as the same characters must be together.
20 |
21 | Example 3:
22 |
23 | Input: s = "Aabb"
24 | Output: "bbAa"
25 | Explanation: "bbaA" is also a valid answer, but "Aabb" is incorrect.
26 | Note that 'A' and 'a' are treated as two different characters.
27 |
28 |
--------------------------------------------------------------------------------
/sort-characters-by-frequency/src/main.rs:
--------------------------------------------------------------------------------
1 | fn main() {
2 | println!("{:?}", frequency_sort("tree".to_string()));
3 | println!("{:?}", frequency_sort("cccaaa".to_string()));
4 | println!("{:?}", frequency_sort("Aabb".to_string()));
5 | }
6 |
7 |
8 | pub fn frequency_sort(s: String) -> String {
9 | let mut count: Vec<(char, usize)> = Vec::new();
10 |
11 | for ch in s.chars() {
12 | match count.iter_mut().find(|(c, _)| *c == ch ) {
13 | Some((_, val)) => *val += 1,
14 | None => count.push((ch, 1))
15 | }
16 | }
17 | // println!("{:?}", count);
18 |
19 | count.sort_by_key(|&(_, count)| std::cmp::Reverse(count));
20 | // println!("{:?}",count);
21 |
22 | let mut res: String = String::from("");
23 | for (k, v) in count{
24 | // println!("{:?} {}", k, v);
25 | for times in 0..v {
26 | res.push(k.clone());
27 | // println!("{}",res);
28 | }
29 | }
30 |
31 | res
32 | }
--------------------------------------------------------------------------------
/two-sum/Cargo.lock:
--------------------------------------------------------------------------------
1 | # This file is automatically @generated by Cargo.
2 | # It is not intended for manual editing.
3 | version = 3
4 |
5 | [[package]]
6 | name = "two-sum"
7 | version = "0.1.0"
8 |
--------------------------------------------------------------------------------
/two-sum/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "two-sum"
3 | version = "0.1.0"
4 | edition = "2021"
5 |
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 |
8 | [dependencies]
9 |
--------------------------------------------------------------------------------
/two-sum/src/main.rs:
--------------------------------------------------------------------------------
1 | #[allow(unused)]
2 | fn main () {
3 | let nums: Vec = vec![3,2,4];
4 | let target: i32 = 6;
5 |
6 | let res: Vec = two_sum(nums, target);
7 | println!("{:?}", res);
8 | }
9 |
10 | #[allow(unused)]
11 | pub fn two_sum(nums: Vec, target: i32) -> Vec {
12 | let mut res: Vec = Vec::new();
13 | let lenth = nums.len();
14 |
15 | for (i, item) in nums.iter().enumerate() {
16 |
17 | for j in (i+1)..lenth {
18 | if nums[i] + nums[j] == target {
19 | vec![i as i32, j as i32 ];
20 | res.push(i as i32);
21 | res.push(j as i32);
22 |
23 | return res
24 | }
25 | }
26 | }
27 | res
28 | }
29 |
30 |
--------------------------------------------------------------------------------
/valid-parenthesis/Cargo.lock:
--------------------------------------------------------------------------------
1 | # This file is automatically @generated by Cargo.
2 | # It is not intended for manual editing.
3 | version = 3
4 |
5 | [[package]]
6 | name = "valid-parenthesis"
7 | version = "0.1.0"
8 |
--------------------------------------------------------------------------------
/valid-parenthesis/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "valid-parenthesis"
3 | version = "0.1.0"
4 | edition = "2021"
5 |
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 |
8 | [dependencies]
9 |
--------------------------------------------------------------------------------
/valid-parenthesis/desc.txt:
--------------------------------------------------------------------------------
1 | Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
2 |
3 | An input string is valid if:
4 |
5 | Open brackets must be closed by the same type of brackets.
6 | Open brackets must be closed in the correct order.
7 | Every close bracket has a corresponding open bracket of the same type.
8 |
9 |
10 |
11 | Example 1:
12 |
13 | Input: s = "()"
14 | Output: true
15 |
16 | Example 2:
17 |
18 | Input: s = "()[]{}"
19 | Output: true
20 |
21 | Example 3:
22 |
23 | Input: s = "(]"
24 | Output: false
25 |
26 |
--------------------------------------------------------------------------------
/valid-parenthesis/src/main.rs:
--------------------------------------------------------------------------------
1 | fn main() {
2 | let s = "()[]{}".to_string();
3 | let status = is_valid(s);
4 | println!("{}", status);
5 | }
6 |
7 | pub fn is_valid(s: String) -> bool {
8 | let mut temp_s: Vec = Vec::new();
9 |
10 | for ch in s.chars() {
11 | match ch {
12 | ')' => {
13 | if let Some('(') = temp_s.pop() {
14 | continue;
15 | } else {
16 | return false;
17 | }
18 | }
19 | '}' => {
20 | if let Some('{') = temp_s.pop() {
21 | continue;
22 | } else {
23 | return false;
24 | }
25 | }
26 | ']' => {
27 | if let Some('[') = temp_s.pop() {
28 | continue;
29 | } else {
30 | return false;
31 | }
32 | }
33 | _ => temp_s.push(ch),
34 | }
35 | }
36 |
37 | temp_s.is_empty()
38 | }
39 |
--------------------------------------------------------------------------------