LeetCode


Jan. 19, 2022

LeetCode 605. Can Place Flowers

/**
 * @param {number[]} flowerbed
 * @param {number} n
 * @return {boolean}
 */
 var  canPlaceFlowers   = function (flowerbed , n ) {
     for  ( let  i   =   0 ; i  < flowerbed .length ; i  ++ ) {
         if  (flowerbed [i ]  ==   0
            &&  (i   ==   0   ||  flowerbed [i  -  1 ]  ==   0 )
            &&  (i   ==  flowerbed .length  -  1   ||  flowerbed [i  +  1 ]  ==   0 )) {
            n  --
            flowerbed [i ]  =   1
             if  (n   <   1 )
                 return true
        }
    }

     return  n   <=   0
};

Jan. 14, 2022

LeetCode 1268. Search Suggestions System

/**
 * @param {string[]} products
 * @param {string} searchWord
 * @return {string[][]}
 */
 var  suggestedProducts   = function (products , searchWord ) {
    products .sort ((a , b ) => {
         if  (a   >  b )  return   1
         if  (a   <  b )  return   -  1
         return   0
    })

     const  r   =  []

     for  ( let  i   =   1 ; i  <= searchWord .length ; i  ++ ) {
         const  arr   =  products .filter ((s ) => s .startsWith (searchWord .substring ( 0 , i ))).slice ( 0 ,  3 )
       //console.log(searchWord.substring(0, i))
         r .push (arr )
    }

     return  r
};

Jan. 12, 2022

LeetCode 253. Meeting Rooms II

Lack of built-in Priority Queues in JavaScript makes it a bit hard to do problems like this. I end looking at the solution:

/**
 * @param {number[][]} intervals
 * @return {number}
 */
 var  minMeetingRooms   = function (intervals ) {
     if  (intervals .length   <   1 )  return   0

     const  startTimes   =  []
     const  endTimes   =  []

     for  ( let  i   =   0 ; i  < intervals .length ; i  ++ ) {
        startTimes [i ]  =  intervals [i ][ 0 ]
        endTimes [i ]  =  intervals [i ][ 1 ]
    }

    startTimes .sort ((a , b ) => a  - b )
    endTimes .sort ((a , b ) => a  - b )

     let  startPtr   =   0
     let  endPtr   =   0
     let  rooms   =   0

     for  ( let  i  =  0 ; i  < intervals .length ; i  ++ ) {
         if  (startTimes [i ]  >=  endTimes [endPtr ]) {
            endPtr  ++
        }  else  {
            rooms  ++
        }
    }

     return  rooms
};

Jan. 11, 2022

LeetCode 937. Reorder Data in Log Files

/**
 * @param {string[]} logs
 * @return {string[]}
 */
var reorderLogFiles = function(logs) {

    const sorted = []
    const numLogs = []
    const charLogs = []

    for (let i = 0; i<logs.length; i++) {
        const log = logs[i]
        const tokenized = log.split(&#34; &#34;)
        if (Number.isInteger(parseInt(tokenized[1]))) {
            numLogs.push(log)
        } else {
            charLogs.push(log)
        }
    }

    charLogs.sort(function (a, b) {
        const stra = a.substr(a.indexOf(' ') + 1)
        const strb = b.substr(b.indexOf(' ') + 1)
        if (stra > strb) {
            return 1
        }
        if (stra < strb) {
            return -1
        }

        const ida = a.substr(0, a.indexOf(' '))
        const idb = b.substr(0, b.indexOf(' '))
        //console.log({ida})
        if (ida > idb) {
            return 1
        }
        if (ida < idb) {
            return -1
        }

        return 0
    })

    return [...charLogs, ...numLogs]

};

Jan. 6, 2022

LeetCode 49. Group Anagrams

/**
 * @param {string[]} strs
 * @return {string[][]}
 */
var groupAnagrams = function(strs) {
    const map = []

    for (let i = 0; i<strs.length; i++) {
        const str = strs[i].split('').sort().join('')
        if (!map[str]) map[str] = []
        map[str].push(strs[i])
    }
    const ans = []
    for (let k in map) {
        ans.push(map[k])
    }
    return ans
};

Jan. 5, 2022

LeetCode 71. Simplify Path

/**
 * @param {string} path
 * @return {string}
 */
var simplifyPath = function(path) {
    const simple = [];
    const splitPath = path.split(&#34;/&#34;).filter(x => x.length>0 && x !== '.')

    for (let i = 0; i<splitPath.length; i++) {
        if (splitPath[i] === '..') {
            simple.pop()
        } else {
            simple.push(splitPath[i])
        }

    }

    return `/${simple.join('/')}`
};

Dec. 31, 2021

LeetCode 50. Pow(x, n)

I got stuck on this problem, even after looking at answers, I could not follow algorithm. Following video really helped me understand it:

Here is my solution after watching this video:

/**
 * @param {number} x
 * @param {number} n
 * @return {number}
 */
 var  myPow   = function (x , n ) {
     if  (x   ==   0 )  return   0

     if  (n   ==   0 )  return   1

     if  (n   <   0 ) {
        x   =   1  / x
        n   =   -  1   *  n
    }

     const  half   =  myPow (x , Math.floor (n  /  2 ))
     let  ans   =  half   *  half

     if  (n  %  2   ==   1 ) ans   =  x   *  ans

     return  ans
};

Dec. 30, 2021

LeetCode 1570. Dot Product of Two Sparse Vectors

My solution in JavaScript:

/**
 * @param {number[]} nums
 * @return {SparseVector}
 */
 var  SparseVector   = function (nums ) {
     const  x   = new  Map ()
     for  ( let  i   =   0 ; i   <  nums .length ; i  ++ ) {
         if  (nums [i ]  !=   0 ) {
            x .set (i , nums [i ])
        }
    }
     this.map   =  x
     this.length   =  nums .length
     return this
};


// Return the dotProduct of two sparse vectors
/**
 * @param {SparseVector} vec
 * @return {number}
 */
SparseVector .prototype .dotProduct   = function (vec ) {
     let  ans   =   0 ;

     for  ( let  i   =   0 ; i   <  vec .length ; i  ++ ) {
         if  (vec .map .has (i )  && this.map .has (i )) {
            ans   +=  vec .map .get (i )  * this.map .get (i )
        }
    }

     return  ans
};

// Your SparseVector object will be instantiated and called as such:
// let v1 = new SparseVector(nums1);
// let v2 = new SparseVector(nums2);
// let ans = v1.dotProduct(v2);

Nov. 4, 2021

Leetcode 92: Reverse Linked List II

Here is my leetcode solution in JavaScript:

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @param {number} left
 * @param {number} right
 * @return {ListNode}
 */
var reverseBetween = function(head, left, right) {
    let currPos = 1;
    let currNode = head;
    let startNode = head;
    let endNode = null;

    while(currPos < left) {
        startNode = currNode;
        currNode = currNode.next;
        currPos++;
    }

    let newList = null;
    let tail = currNode;

    while (currPos <= right) {
        const next = currNode.next;
        currNode.next = newList;
        newList = currNode;
        currNode = next;
        currPos++;
    }

    startNode.next = newList;
    tail.next = currNode;

    if (left > 1) {
        return head;
    }

    return newList;


};

Link to problem.

Jun. 8, 2021

LeetCode 206. Reverse Linked List

Here is a quick solution to Reverse Linked List problem.

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var reverseList = function(head) {
    let curr = head;
    let prev = null;

    while (curr) {
        let next = curr.next;
        curr.next = prev;
        prev = curr;
        curr = next;
    }

    return prev;
};

May. 21, 2021

LeetCode 560. Subarray Sum Equals K

Brute Force Solution to Subarray Sum Equals K problem from LeetCode:

/**
 * @param {number[]} nums
 * @param {number} k
 * @return {number}
 */
var subarraySum = function(nums, k) {
    let ans = 0;

    for (let i=0; i<nums.length; i++) {
        let currSum = nums[i];
        if (currSum === k) ans++;
        for (let j=i+1; j<nums.length; j++) {
            currSum += nums[j];
            if (currSum === k) ans++;

        }
    }

    return ans;
};

Optimized solution after cheating a bit:

/**
 * @param {number[]} nums
 * @param {number} k
 * @return {number}
 */
var subarraySum = function(nums, k) {
    let ans = 0;
    const m = new Map();
    let sum=0;
    m.set(sum, 1);

    for (let i=0; i<nums.length; i++) {
        sum += nums[i];

        if (m.has(sum-k)) {
            ans += m.get(sum-k);
        }

        if (!m.has(sum)) {
            m.set(sum, 1);
        } else {
            m.set(sum, m.get(sum) + 1);
        }

    }

    return ans;
};

Runtime: 96 ms, faster than 94.76% of JavaScript online submissions for Subarray Sum Equals K.

May. 19, 2021

LeetCode 2. Add Two Numbers

Here is my solution to Add Two Numbers problem in PHP:

/**
 * Definition for a singly-linked list.
 * class ListNode {
 *     public $val = 0;
 *     public $next = null;
 *     function __construct($val = 0, $next = null) {
 *         $this->val = $val;
 *         $this->next = $next;
 *     }
 * }
 */
class Solution {

  /**
    * @param ListNode $l1
    * @param ListNode $l2
    * @return ListNode
    */
    function addTwoNumbers($l1, $l2) {
        $ans = new ListNode(0, null);
        $p = $l1;
        $q = $l2;
        $current = $ans;
        $carry=0;

        while ($p != null || $q != null) {
            $x = isset($p) ? $p->val : 0;
            $y = isset($q) ? $q->val : 0;
            $sum = $carry + $x + $y;
            $carry = (int) ($sum/10);
            $current->next = new ListNode($sum%10);
            $current = $current->next;
            if ($p != null) $p = $p->next;
            if ($q != null) $q = $q->next;
        }
        if ($carry > 0) {
            $current->next = new ListNode($carry);
        }

        return $ans->next;
    }
}

May. 16, 2021

LeetCode 7. Reverse Integer

My initial solution for Reverse Integer problem:

/**
 * @param {number} x
 * @return {number}
 */
var reverse = function(x) {

    let ans = '';
    if (x<0) {
        ans = '-';
        x*=-1;
    }

    str = x.toString();

    for (let i=str.length-1; i>=0; i--) {
        ans += str[i];
    }

    ans = parseInt(ans);
    if (ans>2**31-1 || ans<(-2)**31) {
        return 0;
    }
    return ans;
};

Results

Runtime: 104 ms, faster than 34.78% of JavaScript online submissions for Reverse Integer.

Memory Usage: 40.5 MB, less than 33.80% of JavaScript online submissions for Reverse Integer.

May. 12, 2021

LeetCode 3. Longest Substring Without Repeating Characters

Here is my solution in PHP to this problem.

class Solution {

  /**
    * @param String $s
    * @return Integer
    */
    function lengthOfLongestSubstring($s) {
        $n = strlen($s);
        $ans = 0;
        $i = 0;
        $j = 0;

        $arr = [];

        while ($i < $n && $j < $n) {
            if (!in_array($s[$j], $arr)) {
                $arr[] = $s[$j++];
                $ans = max($ans, $j-$i);
            } else {
                array_splice($arr, 0, 1);
                $i++;
            }
        }


        return $ans;
    }
}

And here is solution JavaScript based on this Udemy lesson:

May. 8, 2021

LeetCode 1664: Ways to Make a Fair Array

I tried to do this all by myself but got stuck, ended up transpiling this solution in PHP.

class Solution {

  /**
    * @param Integer[] $nums
    * @return Integer
    */
    function waysToMakeFair($nums) {
        $len = count($nums);
        $ans = 0;

        $leftOdd = 0;
        $rightOdd = 0;
        $leftEven = 0;
        $rightEven = 0;

        for ($i=0; $i<$len; $i++) {
            if ($i%2 === 0)
                $rightEven += $nums[$i];
            else
                $rightOdd += $nums[$i];
        }

        for ($i=0; $i<$len; $i++) {
            if ($i%2 === 0)
                $rightEven -= $nums[$i];
            else
                $rightOdd -= $nums[$i];

            if ($leftEven + $rightOdd === $rightEven + $leftOdd) $ans++;

            if ($i%2 === 0)
                $leftEven += $nums[$i];
            else
                $leftOdd += $nums[$i];
        }

        return $ans;
    }
}

May. 7, 2021

LeetCode 20: Valid Parentheses

Here is my solution to this problem in PHP:

/**
 * @param {string} s
 * @return {boolean}
 */
var isValid = function(s) {
    const stack = [];
    const brackets = {
        '(': ')',
        '{': '}',
        '[': ']'
    };

    for (i=0; i<s.length; i++) {
        if (s.length === 0) return true;

        const c = s[i];
        if (brackets[c]) {
            stack.push(c);
        } else {
            const lastBracket = stack.pop();
            if (brackets[lastBracket] !== c) return false;
        }
    }

    if (stack.length > 0) return false;

    return true;
};

May. 6, 2021

LeetCode 844. Backspace String Compare

Here is my solution Backspace String Compare problem.

/**
 * @param {string} s
 * @param {string} t
 * @return {boolean}
 */
var backspaceCompare = function(s, t) {
    s = processString(s);
    t = processString(t);
    //console.log({s, t})
    return s===t;
};

let processString = function(s) {
    const a = [];
    let skip = 0;
    for (let i = s.length-1; i >= 0; i--) {
        if (s[i] === '#') {
            skip++;
        } else if (skip > 0) {
            skip--;
        } else {
            a.push(s[i]);
        }
        //console.log({a, skip, i})
    }
    let re = '';
    //console.log({ a: a.length})
    while (a.length > 0) {
        re += a.pop();
        //console.log({i, re, a: a.length})
    }
    return re;
}

Results:

Runtime: 80 ms, faster than 73.76% of JavaScript online submissions for Backspace String Compare.

May. 6, 2021

Leetcode 690: Employee Importance Solution

Here is another LeetCode solution for Employee Importance Problem.

/**
* Definition for Employee.
* class Employee {
*     public $id = null;
*     public $importance = null;
*     public $subordinates = array();
*     function __construct($id, $importance, $subordinates) {
*         $this->id = $id;
*         $this->importance = $importance;
*         $this->subordinates = $subordinates;
*     }
* }
*/

class Solution {
/**
 * @param Employee[] $employees
 * @param Integer $id
 * @return Integer
 */

function getImportance($employees, $id) {
  if (empty($employees)) return 0;
  $emap = [];
  foreach ($employees as $e) {
    $emap[$e->id] = $e;
  }

  return $this->recurse($emap, $id);
 }

function recurse($emap, $id) {
  $e = $emap[$id];
  $ans = $e->importance;
  foreach ($e->subordinates as $sub) {
    $ans += $this->recurse($emap, $sub);
  }
  return $ans;
 }
}

May. 6, 2021

LeetCode 1249. Minimum Remove to Make Valid Parentheses

Here is my solution to this problem:

/**
 * @param {string} s
 * @return {string}
 */
var minRemoveToMakeValid = function(s) {
    const stack = [];
    const charArray = s.split(&#34;&#34;);
    const rightBracketsToRemove = [];

    for (let i=0;i<charArray.length;i++) {
        if (charArray[i] === '(') {
            stack.push(i);
        } else if (charArray[i] === ')' && stack.length > 0) {
            stack.pop();
        } else if (charArray[i] === ')') {
            charArray[i] = '';
        }
    }

    while (stack.length > 0) {
        const i = stack.pop();
        charArray[i] = '';
    }

    return charArray.join('');
};

May. 5, 2021

Leetcode 13: Roman to Integers

Here is my solution to this problem in PHP:


    private $v = ['M' = > 1000, 'D' = > 500, 'C' = > 100, 'L' = > 50, 'X' = > 10, 'V' = > 5, 'I' = > 1];
  /**
    * @param String $s
    * @return Integer
    */
    function romanToInt($s) {
        $n = 0;
        $last = '';
        for ($i=0;$i < strlen  ($s  );   $i++)   {
             $n   +=   $this-  >v[$s[$i]];
            if (($s[$i] == 'V' || $s[$i] == 'X')  &&  $last == 'I') {
                $n = $n - 2;
            } elseif (($s[$i] == 'L' || $s[$i] == 'C')  &&  $last == 'X') {
                $n -= 20;
            } elseif (($s[$i] == 'D' || $s[$i] == 'M')  &&  $last == 'C') {
                $n -= 200;
            }
            $last = $s[$i];
        }

        return $n;
    }
}

May. 4, 2021

HackerRank: New Year Chaos

Here is my solution to New Years Chaos problem from HackerRank. The first solution had a bug:

  <pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-js" data-lang="js">function minimumBribes (q ) {
    let bribes   =  0 ;

    for  (let i  = 0 ;i   <q .length  - 2 ;i++ ) {
        if  (q [i ]  -  (i  + 1 )   >  2 ) {
           console .log ( 'Too chaotic' );
            return ;
        }
         // compare index to element, works great except when a smaller element is pushed way back
           if  (q [i ]  -  (i  + 1 )   >  0 ) {
         bribes   += q [i ]  -  (i  + 1 );
        }
    }
   console .log (bribes );
}

Second solution had O(n^2) complexity:

May. 3, 2021

LeetCode 200: Number of Islands

I had to watch some YouTube videos for the solution to this problem. I am not sure if this is the best solution though, one day I will revisit it.


  /**
    * @param String[][] $grid
    * @return Integer
    */
    function numIslands($grid) {
        $count = 0;

        for ($i=0; $i < count  ($grid  );   $i++)   {
           for   ($j  =  0;   $j   <count  ($grid  [$i  ]);   $j++)   {
               if   ($grid  [$i  ][$j  ]   ==   &#34;1  &#34;)   {
                     $count++;
                     // zero out rest of 1s
                     $this-  >zeroOut($grid, $i, $j);
                }
            }
        }

        return $count;
    }

    function zeroOut( & $grid, $i, $j) {
        if ($i < 0   ||   $i  >=count($grid) || $j < 0   ||   $j  >=count($grid[$i]) || $grid[$i][$j] == &#34;0&#34;)
            return;

        $grid[$i][$j] = &#34;0&#34;;

        $this- >zeroOut($grid, $i-1, $j);
        $this- >zeroOut($grid, $i+1, $j);
        $this- >zeroOut($grid, $i, $j-1);
        $this- >zeroOut($grid, $i, $j+1);
    }
}

May. 2, 2021

LeetCode 42. Trapping Rain Water

My solution to LeetCode 42. Trapping Rain Water in JavaScript.

/**
  * @param {number[]} height
  * @return {number}
  */
var trap   =  function (height ) {
    let maxLeft   =  0 ,maxRight   =  0 ;

    let left   =  0 ;
    let right   = height .length   - 1 ;
    let total   =  0 ;

    while  (left    <right ) {
        if  (height [left ]   <height [right ]) {
            if  (height [left ]  >maxLeft ) {
               maxLeft   = height [left ];
            } else  {
              total   += maxLeft  -height [left ]
            }
           left++ ;
        } else  {
            if  (height [right ]  >maxRight ) {
               maxRight   = height [right ];
            } else  {
              total   += maxRight  -height [right ]
            }
           right  -- ;
        }
    }
    return total ;
};

May. 2, 2021

LeetCode 1089: Duplicate Zeros

LeetCode 1089: Duplicate Zeros solution in PHP.


  /**
    * @param Integer[] $arr
    * @return NULL
    */
    function duplicateZeros( & $arr) {
        $len = count($arr);
        for ($i=0; $i   < $len; $i++) {
            if (0 === $arr[$i]) {
                array_splice($arr, $i++, 0, 0);
            }
        }
        array_splice($arr, $len);
    }
}

Apr. 30, 2021

LeetCode 11. Container With Most Water

Here is my solution to Container with Most Water in JavaScript.

/**
  * @param {number[]} height
  * @return {number}
  */
var maxArea   =  function (height ) {
    let left   =  0 ;
    let right   = height .length  - 1 ;
    let maxWater   =  0 ;

    while  (left    <right ) {
        const water   =  (right  -left )  *  Math.min (height [left ],height [right ]);

        if  (water    > maxWater ) {
           maxWater   = water ;
        }

        if  (height [left ]   <height [right ]) {
           left++ ;
        } else  {
           right  -- ;
        }
    }

    return maxWater ;
};

Apr. 29, 2021

LeetCode 1: Two Sum

/**
  * @param {number[]} nums
  * @param {number} target
  * @return {number[]}
  */
var twoSum   =  function (nums ,target ) {
    const numsToFind   =  {};

    for (let i = 0; i<nums.length; i++ ) {
        const numToFind   = nums [i ];
        if  (numsToFind [numToFind ]   >=  0 ) {
            return  [i ,numsToFind [numToFind ]];
        }
       numsToFind [target   - numToFind ]  = i ;
    }
};

My solution for Two Sum problem in PHP.

Apr. 25, 2021

LeetCode 88: Merge Sorted Array solution

Here is my solution for Merge Sorted Array problem in PHP. This is not the most efficient solution.

 class Solution {

  /**
    * @param Integer[] $nums1
    * @param Integer $m
    * @param Integer[] $nums2
    * @param Integer $n
    * @return NULL
    */
    function merge(&$nums1, $m, $nums2, $n) {
        if ($n == 0) {
            return;
        }

        if ($m == 0) {
            for ($i=0; $i  < $n; $i++) {
                $nums1[$i] = $nums2[$i];
            }
        }

        $i = 0;
        $j = 0;

        while ($i  < $m  &&  $j  < $n) {
            if ($nums1[$i]  < =$nums2[$j]) {
                $i++;
            } else {
                $this->array_insert($nums1, $i++, $nums2[$j]);
                $m++;
                $j++;
            }
        }

        while ($j   < $n) {
            $nums1[$i++] = $nums2[$j++];
        }

    }

    function array_insert( & $arr, $i, $num) {
        $endArr = array_slice($arr, $i);
        $arr[$i] = $num;

        for ($x=$i+1; $x < count  ($arr);   $x++)   {
             $arr  [$x  ]   = array_shift  ($endArr);
         }
     }
 }

Apr. 21, 2021

LeetCode 26 – Remove Duplicates from Sorted Array

Here is my solution to Remove Duplicates from Sorted Array problem in JavaScript

/**
 * @param {number[]} nums
 * @return {number}
 */
var removeDuplicates = function(nums) {
    let i=0;

    while (i<nums.length-1) {
        if (nums[i] === nums[i+1]) {
            nums.splice(i+1, 1);
        } else {
            i++;
        }
    }

    return nums.length;
};

Results

Runtime: 108 ms, faster than 33.69% of JavaScript online submissions for Remove Duplicates from Sorted Array.Memory

Usage: 40.6 MB, less than 89.66% of JavaScript online submissions for Remove Duplicates from Sorted Array.

Apr. 20, 2021

LeetCode #73: Set Matrix Zeroes

Here is my solution to Set Matrix Zeros

problem in PHP:

class Solution {

  /**
    * @param Integer[][] $matrix
    * @return NULL
    */
    function setZeroes(&$matrix) {
        $rowsToZeroOut = [];
        $colsToZeroOut = [];
        for ($i=0; $i<count($matrix); $i++) {
            for ($j=0; $j<count($matrix[$i]); $j++) {
                if ($matrix[$i][$j] === 0) {
                    $rowsToZeroOut[] = $i;
                    $colsToZeroOut[] = $j;
                }
            }
        }

        foreach($rowsToZeroOut as $r) {
            for($i=0; $i<count($matrix[$r]); $i++) {
               $matrix[$r][$i] = 0;
            }
        }

        foreach($colsToZeroOut as $c) {
            for($i=0; $i<count($matrix); $i++) {
               $matrix[$i][$c] = 0;
            }
        }
    }
}

Results

Runtime: 52 ms, faster than 13.33% of PHP online submissions for Set Matrix Zeroes. Memory Usage: 19.8 MB, less than 80.00% of PHP online submissions for Set Matrix Zeroes.