Skip to content

Commit

Permalink
Added js tasks
Browse files Browse the repository at this point in the history
  • Loading branch information
javadev committed Dec 19, 2024
1 parent 1788627 commit 64b62be
Show file tree
Hide file tree
Showing 51 changed files with 1,927 additions and 0 deletions.
32 changes: 32 additions & 0 deletions src/main/js/com_github_leetcode/node.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
class Node {
constructor(val, next, random) {
this.val = val ?? 0
this.next = next ?? null
this.random = random ?? null
}

toString() {
const result = []
let curr = this
while (curr !== null) {
const result2 = []
result2.push(String(curr.val))
if (curr.random === null) {
result2.push('null')
} else {
let randomIndex = 0
let curr2 = this
while (curr2?.next !== null && curr2 !== curr.random) {
randomIndex++
curr2 = curr2.next
}
result2.push(String(randomIndex))
}
result.push(`[${result2.join(',')}]`)
curr = curr.next
}
return `[${result.join(',')}]`
}
};

export { Node }
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
121\. Best Time to Buy and Sell Stock

Easy

You are given an array `prices` where `prices[i]` is the price of a given stock on the <code>i<sup>th</sup></code> day.

You want to maximize your profit by choosing a **single day** to buy one stock and choosing a **different day in the future** to sell that stock.

Return _the maximum profit you can achieve from this transaction_. If you cannot achieve any profit, return `0`.

**Example 1:**

**Input:** prices = [7,1,5,3,6,4]

**Output:** 5

**Explanation:** Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.

Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.

**Example 2:**

**Input:** prices = [7,6,4,3,1]

**Output:** 0

**Explanation:** In this case, no transactions are done and the max profit = 0.

**Constraints:**

* <code>1 <= prices.length <= 10<sup>5</sup></code>
* <code>0 <= prices[i] <= 10<sup>4</sup></code>
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
// #Easy #Top_100_Liked_Questions #Top_Interview_Questions #Array #Dynamic_Programming
// #Data_Structure_I_Day_3_Array #Dynamic_Programming_I_Day_7 #Level_1_Day_5_Greedy #Udemy_Arrays
// #Big_O_Time_O(N)_Space_O(1) #2024_12_15_Time_1_ms_(97.34%)_Space_59.1_MB_(51.64%)

/**
* @param {number[]} prices
* @return {number}
*/
var maxProfit = function(prices) {
let maxProfit = 0
let min = prices[0]

for (let i = 1; i < prices.length; i++) {
if (prices[i] > min) {
maxProfit = Math.max(maxProfit, prices[i] - min)
} else {
min = prices[i]
}
}

return maxProfit
};

export { maxProfit }
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
124\. Binary Tree Maximum Path Sum

Hard

A **path** in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence **at most once**. Note that the path does not need to pass through the root.

The **path sum** of a path is the sum of the node's values in the path.

Given the `root` of a binary tree, return _the maximum **path sum** of any **non-empty** path_.

**Example 1:**

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

**Input:** root = [1,2,3]

**Output:** 6

**Explanation:** The optimal path is 2 -> 1 -> 3 with a path sum of 2 + 1 + 3 = 6.

**Example 2:**

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

**Input:** root = [-10,9,20,null,null,15,7]

**Output:** 42

**Explanation:** The optimal path is 15 -> 20 -> 7 with a path sum of 15 + 20 + 7 = 42.

**Constraints:**

* The number of nodes in the tree is in the range <code>[1, 3 * 10<sup>4</sup>]</code>.
* `-1000 <= Node.val <= 1000`
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
// #Hard #Top_100_Liked_Questions #Top_Interview_Questions #Dynamic_Programming #Depth_First_Search
// #Tree #Binary_Tree #Udemy_Tree_Stack_Queue #Big_O_Time_O(N)_Space_O(N)
// #2024_12_15_Time_1_ms_(98.34%)_Space_59.8_MB_(12.47%)

/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var maxPathSum = function(root) {
let max = Number.MIN_SAFE_INTEGER

const helper = (node) => {
if (node === null) {
return 0
}

// Calculate max sum on the left and right subtrees, avoiding negatives
const left = Math.max(0, helper(node.left))
const right = Math.max(0, helper(node.right))

// Current path sum including the node
const current = node.val + left + right

// Update the global max if the current path sum is greater
max = Math.max(max, current)

// Return the max sum of the path passing through the current node
return node.val + Math.max(left, right)
}

helper(root)
return max
};

export { maxPathSum }
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
128\. Longest Consecutive Sequence

Medium

Given an unsorted array of integers `nums`, return _the length of the longest consecutive elements sequence._

You must write an algorithm that runs in `O(n)` time.

**Example 1:**

**Input:** nums = [100,4,200,1,3,2]

**Output:** 4

**Explanation:** The longest consecutive elements sequence is `[1, 2, 3, 4]`. Therefore its length is 4.

**Example 2:**

**Input:** nums = [0,3,7,2,5,8,4,6,0,1]

**Output:** 9

**Constraints:**

* <code>0 <= nums.length <= 10<sup>5</sup></code>
* <code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code>
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// #Medium #Top_100_Liked_Questions #Top_Interview_Questions #Array #Hash_Table #Union_Find
// #Big_O_Time_O(N_log_N)_Space_O(1) #2024_12_15_Time_31_ms_(93.87%)_Space_59_MB_(96.32%)

/**
* @param {number[]} nums
* @return {number}
*/
var longestConsecutive = function(nums) {
if (nums.length === 0) {
return 0
}
nums.sort((a, b) => a - b)
let max = Number.MIN_SAFE_INTEGER
let thsMax = 1
for (let i = 0; i < nums.length - 1; i++) {
if (nums[i + 1] === nums[i] + 1) {
thsMax += 1
continue
}
if (nums[i + 1] === nums[i]) {
continue
}
max = Math.max(max, thsMax)
thsMax = 1 // NOSONAR
}
return Math.max(max, thsMax)
};

export { longestConsecutive }
24 changes: 24 additions & 0 deletions src/main/js/g0101_0200/s0131_palindrome_partitioning/readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
131\. Palindrome Partitioning

Medium

Given a string `s`, partition `s` such that every substring of the partition is a **palindrome**. Return all possible palindrome partitioning of `s`.

A **palindrome** string is a string that reads the same backward as forward.

**Example 1:**

**Input:** s = "aab"

**Output:** [["a","a","b"],["aa","b"]]

**Example 2:**

**Input:** s = "a"

**Output:** [["a"]]

**Constraints:**

* `1 <= s.length <= 16`
* `s` contains only lowercase English letters.
39 changes: 39 additions & 0 deletions src/main/js/g0101_0200/s0131_palindrome_partitioning/solution.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
// #Medium #Top_100_Liked_Questions #Top_Interview_Questions #String #Dynamic_Programming
// #Backtracking #Big_O_Time_O(N*2^N)_Space_O(2^N*N)
// #2024_12_15_Time_21_ms_(89.90%)_Space_71.7_MB_(95.05%)

/**
* @param {string} s
* @return {string[][]}
*/
var partition = function(s) {
const res = []
backtracking(res, [], s, 0)
return res
};

const backtracking = (res, currArr, s, start) => {
if (start === s.length) {
res.push([...currArr]) // Add a copy of the current array to the result
return
}

for (let end = start; end < s.length; end++) {
if (!isPalindrome(s, start, end)) {
continue
}
currArr.push(s.substring(start, end + 1)) // Add the current substring
backtracking(res, currArr, s, end + 1) // Recurse to the next part
currArr.pop() // Remove the last element to backtrack
}
};

const isPalindrome = (s, start, end) => {
while (start < end && s[start] === s[end]) {
start++
end--
}
return start >= end
};

export { partition }
31 changes: 31 additions & 0 deletions src/main/js/g0101_0200/s0136_single_number/readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
136\. Single Number

Easy

Given a **non-empty** array of integers `nums`, every element appears _twice_ except for one. Find that single one.

You must implement a solution with a linear runtime complexity and use only constant extra space.

**Example 1:**

**Input:** nums = [2,2,1]

**Output:** 1

**Example 2:**

**Input:** nums = [4,1,2,1,2]

**Output:** 4

**Example 3:**

**Input:** nums = [1]

**Output:** 1

**Constraints:**

* <code>1 <= nums.length <= 3 * 10<sup>4</sup></code>
* <code>-3 * 10<sup>4</sup> <= nums[i] <= 3 * 10<sup>4</sup></code>
* Each element in the array appears twice except for one element which appears only once.
17 changes: 17 additions & 0 deletions src/main/js/g0101_0200/s0136_single_number/solution.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
// #Easy #Top_100_Liked_Questions #Top_Interview_Questions #Array #Bit_Manipulation
// #Data_Structure_II_Day_1_Array #Algorithm_I_Day_14_Bit_Manipulation #Udemy_Integers
// #Big_O_Time_O(N)_Space_O(1) #2024_12_15_Time_0_ms_(100.00%)_Space_52.3_MB_(38.50%)

/**
* @param {number[]} nums
* @return {number}
*/
var singleNumber = function(nums) {
let res = 0
for (const num of nums) {
res ^= num
}
return res
};

export { singleNumber }
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
138\. Copy List with Random Pointer

Medium

A linked list of length `n` is given such that each node contains an additional random pointer, which could point to any node in the list, or `null`.

Construct a [**deep copy**](https://en.wikipedia.org/wiki/Object_copying#Deep_copy) of the list. The deep copy should consist of exactly `n` **brand new** nodes, where each new node has its value set to the value of its corresponding original node. Both the `next` and `random` pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original list and copied list represent the same list state. **None of the pointers in the new list should point to nodes in the original list**.

For example, if there are two nodes `X` and `Y` in the original list, where `X.random --> Y`, then for the corresponding two nodes `x` and `y` in the copied list, `x.random --> y`.

Return _the head of the copied linked list_.

The linked list is represented in the input/output as a list of `n` nodes. Each node is represented as a pair of `[val, random_index]` where:

* `val`: an integer representing `Node.val`
* `random_index`: the index of the node (range from `0` to `n-1`) that the `random` pointer points to, or `null` if it does not point to any node.

Your code will **only** be given the `head` of the original linked list.

**Example 1:**

![](https://assets.leetcode.com/uploads/2019/12/18/e1.png)

**Input:** head = [[7,null],[13,0],[11,4],[10,2],[1,0]]

**Output:** [[7,null],[13,0],[11,4],[10,2],[1,0]]

**Example 2:**

![](https://assets.leetcode.com/uploads/2019/12/18/e2.png)

**Input:** head = [[1,1],[2,1]]

**Output:** [[1,1],[2,1]]

**Example 3:**

**![](https://assets.leetcode.com/uploads/2019/12/18/e3.png)**

**Input:** head = [[3,null],[3,0],[3,null]]

**Output:** [[3,null],[3,0],[3,null]]

**Constraints:**

* `0 <= n <= 1000`
* <code>-10<sup>4</sup> <= Node.val <= 10<sup>4</sup></code>
* `Node.random` is `null` or is pointing to some node in the linked list.
Loading

0 comments on commit 64b62be

Please sign in to comment.