JavaScript Array Coding question
Published: 2024-06-27 10:04:29

**Finding the Missing Number in an Array from 1 to 100:**

```
function findMissingNumber(nums) {
    const n = 100;
    const expectedSum = (n * (n + 1)) / 2;
    const actualSum = nums.reduce((acc, num) => acc + num, 0);
    return expectedSum - actualSum;
}

console.log(findMissingNumber([...Array(100).keys()].map(n => n + 1).filter(n => n !== 50))); // Example where 50 is missing
```


**Finding the Duplicate Number in an Array:**

```

function findDuplicate(nums) {
    const seen = new Set();
    for (const num of nums) {
        if (seen.has(num)) {
            return num;
        }
        seen.add(num);
    }
    return -1; // If no duplicate found
}

console.log(findDuplicate([1, 2, 3, 4, 4])); // Example with duplicate 4
 
```

**Finding the Largest and Smallest Number in an Unsorted Array:**

```
function findMinMax(nums) {
    let min = nums[0];
    let max = nums[0];
    for (const num of nums) {
        if (num < min) min = num;
        if (num > max) max = num;
    }
    return { min, max };
}

console.log(findMinMax([3, 5, 1, 2, 4])); // Example output: { min: 1, max: 5 }
```

**Finding All Pairs of an Integer Array Whose Sum Equals a Given Number:**


```
function findPairsWithSum(nums, target) {
    const pairs = [];
    const seen = new Set();
    for (const num of nums) {
        const complement = target - num;
        if (seen.has(complement)) {
            pairs.push([complement, num]);
        }
        seen.add(num);
    }
    return pairs;
}

console.log(findPairsWithSum([1, 2, 3, 4, 3], 6)); // Example output: [[3, 3], [2, 4]]
```

**Finding Duplicate Numbers in an Array if It Contains Multiple Duplicates**:


```
function findDuplicates(nums) {
    const seen = new Set();
    const duplicates = new Set();
    for (const num of nums) {
        if (seen.has(num)) {
            duplicates.add(num);
        }
        seen.add(num);
    }
    return Array.from(duplicates);
}

console.log(findDuplicates([1, 2, 3, 4, 3, 2])); // Example output: [2, 3]
```
 **Finding the Starting and Ending Position of a Given Value in a Sorted Array:**

```


function searchRotatedArray(nums, target) {
    let left = 0, right = nums.length - 1;
    while (left <= right) {
        const mid = Math.floor((left + right) / 2);
        if (nums[mid] === target) return mid;
        if (nums[left] <= nums[mid]) {
            if (nums[left] <= target && target < nums[mid]) {
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        } else {
            if (nums[mid] < target && target <= nums[right]) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
    }
    return -1;
}

console.log(searchRotatedArray([4, 5, 6, 7, 0, 1, 2], 0)); // Example output: 4
```
**Finding the Length of the Longest Consecutive Elements Sequence in an Unsorted Array:**


```
function longestConsecutive(nums) {
    const numSet = new Set(nums);
    let longestStreak = 0;
    for (const num of nums) {
        if (!numSet.has(num - 1)) {
            let currentNum = num;
            let currentStreak = 1;
            while (numSet.has(currentNum + 1)) {
                currentNum += 1;
                currentStreak += 1;
            }
            longestStreak = Math.max(longestStreak, currentStreak);
        }
    }
    return longestStreak;
}

console.log(longestConsecutive([100, 4, 200, 1, 3, 2])); // Example output: 4
```
 **Sorting an Integer Array In-Place Using the Quicksort Algorithm:**

```

// javascript
function quicksort(arr, left = 0, right = arr.length - 1) {
    if (left >= right) return;
    const pivot = arr[Math.floor((left + right) / 2)];
    const index = partition(arr, left, right, pivot);
    quicksort(arr, left, index - 1);
    quicksort(arr, index, right);
}

function partition(arr, left, right, pivot) {
    while (left <= right) {
        while (arr[left] < pivot) left++;
        while (arr[right] > pivot) right--;
        if (left <= right) {
            [arr[left], arr[right]] = [arr[right], arr[left]];
            left++;
            right--;
        }
    }
    return left;
}

const arr = [3, 6, 8, 10, 1, 2, 1];
quicksort(arr);
console.log(arr); // Example output: [1, 1, 2, 3, 6, 8, 10]


**Reversing an Array In-Place in Java:**

```


function reverseArray(arr) {
    let left = 0;
    let right = arr.length - 1;
    while (left < right) {
        const temp = arr[left];
        arr[left] = arr[right];
        arr[right] = temp;
        left++;
        right--;
    }
}

const arr = [1, 2, 3, 4, 5];
reverseArray(arr);
console.log(arr); // Example output: [5, 4, 3, 2, 1]
```



 **Converting a Byte Array to String:**

```
// javascript
function byteArrayToString(bytes) {
    return String.fromCharCode(...bytes);
}

console.log(byteArrayToString([104, 101, 108, 108, 111])); // Example output: "hello"
```
**Difference Between an Array and a Linked List:**
```


// text
// Arrays:
// - Fixed size (in many languages).
// - Contiguous memory allocation.
// - O(1) access time for elements via index.
// - O(n) time complexity for insertion and deletion (in the worst case).

// Linked Lists:
// - Dynamic size.
// - Non-contiguous memory allocation.
// - O(n) access time for elements (sequential access).
// - O(1) time complexity for insertion and deletion at the beginning or end.
```
**Binary Search in a Given Array:**

```

// javascript
function binarySearch(arr, target) {
    let left = 0, right = arr.length - 1;
    while (left <= right) {
        const mid = Math.floor((left + right) / 2);
        if (arr[mid] === target) return mid;
        if (arr[mid] < target) left = mid + 1;
        else right = mid - 1;
    }
    return -1; // If the target is not found
}

console.log(binarySearch([1, 2, 3, 4, 5, 6], 4)); // Example output: 3
```

**Finding the Median of Two Sorted Arrays:**

```
function findMedianSortedArrays(nums1, nums2) {
    const merged = mergeSortedArrays(nums1, nums2);
    const n = merged.length;
    if (n % 2 === 0) {
        return (merged[Math.floor((n - 1) / 2)] + merged[Math.floor(n / 2)]) / 2;
    } else {
        return merged[Math.floor(n / 2)];
    }
}

function mergeSortedArrays(arr1, arr2) {
    const merged = [];
    let i = 0, j = 0;
    while (i < arr1.length && j < arr2.length) {
        if (arr1[i] < arr2[j]) {
            merged.push(arr1[i]);
            i++;
        } else {
            merged.push(arr2[j]);
            j++;
        }
    }
    while (i < arr1.length) merged.push(arr1[i++]);
    while (j < arr2.length) merged.push(arr2[j++]);
    return merged;
}

console.log(findMedianSortedArrays([1, 3], [2])); // Example output: 2
console.log(findMedianSortedArrays([1, 2], [3, 4])); // Example output: 2.5

```
** Rotating an Array Left and Right by a Given Number K:**


```
function rotateArrayLeft(arr, k) {
    k = k % arr.length;
    return arr.slice(k).concat(arr.slice(0, k));
}

function rotateArrayRight(arr, k) {
    k = k % arr.length;
    return arr.slice(-k).concat(arr.slice(0, -k));
}

console.log(rotateArrayLeft([1, 2, 3, 4, 5], 2)); // Example output: [3, 4, 5, 1, 2]
console.log(rotateArrayRight([1, 2, 3, 4, 5], 2)); // Example output: [4, 5, 1, 2, 3]
```
**Finding Duplicates from an Unsorted Array:**

```


function findDuplicates(nums) {
    const seen = new Set();
    const duplicates = new Set();
    for (const num of nums) {
        if (seen.has(num)) {
            duplicates.add(num);
        } else {
            seen.add(num);
        }
    }
    return Array.from(duplicates);
}

console.log(findDuplicates([1, 2, 3, 4, 3, 2, 1])); // Example output: [1, 2, 3]
```
**Finding the Starting and Ending Position of a Given Value in a Sorted Array:**

```

function searchRange(nums, target) {
    const result = [-1, -1];
    result[0] = findBound(nums, target, true);
    if (result[0] !== -1) {
        result[1] = findBound(nums, target, false);
    }
    return result;
}

function findBound(nums, target, isFirst) {
    let left = 0, right = nums.length - 1;
    while (left <= right) {
        const mid = Math.floor((left + right) / 2);
        if (nums[mid] === target) {
            if (isFirst) {
                if (mid === left || nums[mid - 1] !== target) {
                    return mid;
                }
                right = mid - 1;
            } else {
                if (mid === right || nums[mid + 1] !== target) {
                    return mid;
                }
                left = mid + 1;
            }
        } else if (nums[mid] < target) {
            left = mid + 1;
        } else {
            right = mid - 1;
        }
    }
    return -1;
}

console.log(searchRange([5, 7, 7, 8, 8, 10], 8)); // Example output: [3, 4]
```

**Finding the Contiguous Subarray with the Largest Sum:**


```
function maxSubArray(nums) {
    let maxSoFar = nums[0];
    let maxEndingHere = nums[0];
    for (let i = 1; i < nums.length; i++) {
        maxEndingHere = Math.max(nums[i], maxEndingHere + nums[i]);
        maxSoFar = Math.max(maxSoFar, maxEndingHere);
    }
    return maxSoFar;
}

console.log(maxSubArray([-2, 1, -3, 4, -1, 2, 1, -5, 4])); // Example output: 6
```