Skip to content

TypeScript: Chapter 1 Two Pointers #54

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions typescript/Two Pointers/is_palindrome_valid.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
function is_palindrome_valid(s: string): boolean {
let left = 0, right = s.length - 1
while (left < right) {
// Skip non-alphanumeric characters from the left.
while (left < right && !isalnum(s[left]))
left++
// Skip non-alphanumeric characters from the right.
while (left < right && !isalnum(s[right]))
right--
// If the characters at the left and right pointers don't
// match, the string is not a palindrome.
if (s[left] !== s[right])
return false
left++
right--
}
return true
}

const isalnum = (c: string): boolean => /^[a-z0-9]+$/i.test(c);
20 changes: 20 additions & 0 deletions typescript/Two Pointers/largest_container.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
function largest_container(heights: number[]): number {
let max_water = 0
let left = 0, right = heights.length - 1
while (left < right) {
// Calculate the water contained between the current pair of
// lines.
let water = Math.min(heights[left], heights[right]) * (right - left)
max_water = Math.max(max_water, water)
// Move the pointers inward, always moving the pointer at the
// shorter line. If both lines have the same height, move both
// pointers inward.
if (heights[left] < heights[right])
left++
else if (heights[left] > heights[right])
right--
else
left++, right--
}
return max_water
}
13 changes: 13 additions & 0 deletions typescript/Two Pointers/largest_container_brute_force.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
function largest_container_brute_force(heights: number[]): number {
let n = heights.length
let max_water = 0
// Find the maximum amount of water stored between all pairs of
// lines.
for (let i = 0; i < n - 1; i++) {
for (let j = i + 1; j < n; j++) {
let water = Math.min(heights[i], heights[j]) * (j - i)
max_water = Math.max(max_water, water)
}
}
return max_water
}
23 changes: 23 additions & 0 deletions typescript/Two Pointers/next_lexicographical_sequence.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
function next_lexicographical_sequence(s: string): string {
let letters = [...s];
// Locate the pivot, which is the first character from the right that breaks
// non-increasing order. Start searching from the second-to-last position.
let pivot = letters.length - 2;
while (pivot >= 0 && letters[pivot] >= letters[pivot + 1])
pivot--;
// If pivot is not found, the string is already in its largest permutation. In
// this case, reverse the string to obtain the smallest permutation.
if (pivot === -1)
return letters.reverse().join('');
// Find the rightmost successor to the pivot.
let rightmost_successor = letters.length - 1;
while (letters[rightmost_successor] <= letters[pivot])
rightmost_successor--;
// Swap the rightmost successor with the pivot to increase the lexicographical
// order of the suffix.
[letters[pivot], letters[rightmost_successor]] = [letters[rightmost_successor], letters[pivot]];
// Reverse the suffix after the pivot to minimize its permutation.
const suffix = letters.slice(pivot + 1).reverse();
letters.splice(pivot + 1, suffix.length, ...suffix);
return letters.join('');
}
18 changes: 18 additions & 0 deletions typescript/Two Pointers/pair_sum_sorted.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
function pair_sum_sorted(nums: number[], target: number): number[] {
let left = 0, right = nums.length - 1
while (left < right) {
let sum = nums[left] + nums[right]
// If the sum is smaller, increment the left pointer, aiming
// to increase the sum toward the target value.
if (sum < target)
left++
// If the sum is larger, decrement the right pointer, aiming
// to decrease the sum toward the target value.
else if (sum > target)
right--
// If the target pair is found, return its indexes.
else
return [left, right]
}
return []
}
10 changes: 10 additions & 0 deletions typescript/Two Pointers/pair_sum_sorted_brute_force.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
function pair_sum_sorted_brute_force(nums: number[], target: number): number[] {
const n = nums.length;
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) {
if (nums[i] + nums[j] === target)
return [i, j]
}
}
return []
}
14 changes: 14 additions & 0 deletions typescript/Two Pointers/shift_zeros_to_the_end.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
function shift_zeros_to_the_end(nums: number[]): void {
// The 'left' pointer is used to position non-zero elements.
let left = 0
// Iterate through the array using a 'right' pointer to locate non-zero
// elements.
for (let right = 0; right < nums.length; right++) {
if (nums[right] !== 0) {
[nums[left], nums[right]] = [nums[right], nums[left]]
// Increment 'left' since it now points to a position already occupied
// by a non-zero element.
left++
}
}
}
15 changes: 15 additions & 0 deletions typescript/Two Pointers/shift_zeros_to_the_end_naive.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
function shift_zeros_to_the_end_naive(nums: number[]): void {
let temp = Array(nums.length).fill(0);
let i = 0
// Add all non-zero elements to the left of 'temp'.
for (let number of nums) {
if (number !== 0) {
temp[i] = number
i++
}
}
// Set 'nums' to 'temp'.
for (let j = 0; j < nums.length; j++) {
nums[j] = temp[j]
}
}
41 changes: 41 additions & 0 deletions typescript/Two Pointers/triplet_sum.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
function triplet_sum(nums: number[]): number[][] {
const triplets = []
nums.sort()
for (let i = 0; i < nums.length; i++) {
// Optimization: triplets consisting of only positive numbers
// will never sum to 0.
if (nums[i] > 0 )
break
// To avoid duplicate triplets, skip 'a' if it's the same as
// the previous number.
if (i > 0 && nums[i] === nums[i - 1])
continue
// Find all pairs that sum to a target of '-a' (-nums[i]).
const pairs = pair_sum_sorted_all_pairs(nums, i + 1, -nums[i])
for (const pair of pairs) {
triplets.push([nums[i]].concat(pair))
}
}
return triplets
}

function pair_sum_sorted_all_pairs(nums: number[], start: number, target: number): number[]{
const pairs = []
let left = start, right = nums.length - 1
while (left < right) {
const sum = nums[left] + nums[right]
if (sum === target) {
pairs.push([nums[left], nums[right]])
left++
// To avoid duplicate '[b, c]' pairs, skip 'b' if it's the
// same as the previous number.
while (left < right && nums[left] === nums[left - 1])
left++
} else if (sum < target) {
left++
} else {
right--
}
}
return pairs
}
20 changes: 20 additions & 0 deletions typescript/Two Pointers/triplet_sum_brute_force.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
function triplet_sum_brute_force(nums: number[]): number[][] {
let n = nums.length
// Use a hash set to ensure we don't add duplicate triplets.
let triplets = new Set()
// Iterate through the indexes of all triplets.
for (let i = 0; i < n - 2; i++) {
for (let j = i + 1; j < n - 1; j++) {
for (let k = j + 1; k < n; k++) {
if (nums[i] + nums[j] + nums[k] === 0) {
// Sort the triplet before including it in the hash set.
// [javascript] convert triplet array into a JSON string to use as a unqiue Set value.
let triplet = JSON.stringify([nums[i], nums[j], nums[k]].sort())
triplets.add(triplet)
}
}
}
}
// [javascript] convert the Set back into an array of triplets.
return Array.from(triplets).map(JSON.parse)
}