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;
 }
}

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("");
    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('');
};

Leetcode 13: Roman to Integers

Here is my solution to this problem in PHP:

class Solution {

    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;
    }
}

Troubleshooting Kubernetes Ingress

Setting up Ingress is an easy process but when it doesn’t work it gets really painful. First, make sure you have Ingress Controller setup correctly. This is in addition to Ingress resource and should be automatically setup by your cloud provider. When I was trying to setup a Kubernetes cluster on IBM Cloud, I ran into a lot of issues. It seems due to my permissions level something went wrong during provisioning of Kubernetes and Ingress Controller was not setup correctly. I went through a lot of steps including recreating alb , ingress resources, etc. The final fix was to login to IBM Cloud as superuser to change Access Policies for the cluster. Once did that, everything just worked magically.

In case of IBM Cloud, here is an excellent list of steps to troubleshoot Ingress issues.


HackerRank: New Year Chaos

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

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:

function minimumBribes(q) {
    let bribes = 0;

    for (let i=0; i<q.length; i++) {
        if (q[i] - (i+1) > 2) {
            console.log('Too chaotic');
            return;
        }
        // if there is a bigger  element before this element
        // then that element must have bribed this element
        for (let j=0; j<i; j++) {
            if (q[i]<q[j]) {
                bribes++;
            }
        }
    }
    console.log(bribes);
}

At this point, I looked up in comments and found an optimal solution:

function minimumBribes(q) {
    let bribes = 0;
    let expectedFirst = 1;
    let expectedSecond = 2;
    let expectedThird = 3;

    for (let i=0; i<q.length-0; i++) {
        if (q[i] == expectedFirst) {
            expectedFirst = expectedSecond;
            expectedSecond = expectedThird;
            ++expectedThird;
        } else if (q[i] == expectedSecond) {
            ++bribes;
            expectedSecond = expectedThird;
            ++expectedThird;
        } else if (q[i] == expectedThird) {
            bribes += 2;
            ++expectedThird;
        } else {
            console.log("Too chaotic");
            return;
        }
    }
    console.log(bribes);
}

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.

class Solution {

    /**
     * @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] == "1") {
                    $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] == "0")
            return;

        $grid[$i][$j] = "0";

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

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;
};

LeetCode 1089: Duplicate Zeros

LeetCode 1089: Duplicate Zeros solution in PHP.

class Solution {

    /**
     * @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);
    }
}

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;
};

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.


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);
        //print_r($endArr);
        $arr[$i] = $num;

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

Finding childcare through your employer

It is amazing how hard it is to find childcare. There are a lot of Facebook groups to find nannies and babysitters. We had been looking for babysitters there but there is high rate of people showing initial interest and then disappearing for a week. We cannot hire someone like that to watch our son.

We decided we should signup with care.com or sittercity.com. However, my colleague reminded that our employer, IBM, has some sort of program to find childcare. That’s when we discovered that IBM indeed has really great options for this. We talked to some of our friends at other companies and turns out pretty much all much employers provide a lot of great options to find childcare. Here three different options that many employers provide.

Daycares

A lot of employers have discount deals with major daycare chains and independent daycares. We get up to 10% discount.

Babysitters or Nannies

There are various types of options here:

Free memberships

We get free membership to sittercity.com to search for babysitters or nannies. Some friends had access to other internal tools for this.

Nanny Placement

While you can search for nannies on sittercity.com, you will need to interview, run background checks, etc. You can hire a Nanny Placement agency that will handle all the initial interview and vetting process for you. They usually charge $1000+. We get 30% or up to $300 off placement fees and found similar discounts at our friends companies.

Day Camps

Again another option for childcare. Many employers have 20-30% discount deals with various day camps.

Emergency Backup Care

This is a life saver. My company subsidize cost of emergency childcare during work hours. Total out of pocket cost for in-home babysitter is $6/hour for us for up to 25 days a year. Our friends also had similar deals. Some friends didn’t had restrictions that it was for only during work hours. So they can use their service for date night etc.


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.


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.


Real Estate

I work as a part-time REALTOR for White Rock Realty. I specialize in new construction homes. Currently, I am offering up to 50% of my commission in buyers’ rebates. If you or you know someone who is buying a new home, please contact me. Visit my site here to search for New Build homes.

If you want to buy a preowned home, I may not be able to help you but I know some great Realtors. Looking for a home with a REALTOR is like going on a date, if you are not a good match, it will make whole process a little less fun. Contact me and I can refer you to someone who will make this complicated process fun and easy for you.

Even if you are not buying or selling a home, feel free to contact me if you have any questions regarding real estate. I love discussing and exploring DFW. I can run reports for you, help you understand real estate processes, contracts, etc. Whatever real estate related question or concern you have, I will help you.


My experience with Open Water Scuba certification in Dallas

This year I crossed off one of my bucket list item, got Open Water Diver certification. I had done scuba diving before at Honolulu. It is among my top 3 best experiences. Ever since that vacation, I had been wanting to get into diving more seriously.

But since we live in land locked Dallas, I didn’t think it was possible or worth it. Then this year in February I saw Groupon from International Scuba and I decided to just go for it. I think Groupon was for $250 but then there was a fine print which said we need to buy our own mask, fins, snorkel, and boots. I bought all this gear from International Scuba as they offered free gear rental for checkout dives. But this added about additional $200.

This certification consist of three parts, online education, in-person classes and training in a pool, and checkout dives in open water body such as lake.

Online classes were easy and interesting. Production quality is sadly extremely low though. It looks like they shot videos in 1980s.

My in-person classes and checkout dives were scheduled in March. It was still pretty cold outside, but International Scuba has nice heated indoors pool. Our instructor was great and very thorough.

This was around the time when COVID19 was spreading in the US but DFW had no such cases yet.

Our checkout dives were at Scuba Ranch in Terrell. Water temperature there was about 60 F then. However, instructor assured that with thick enough wetsuit, we will be fine.

I got 7mm wetsuit but I was still cold in the water but it was bearable. One thing about thick wetsuits is that they increase your buoyancy significantly. We did our training in pool in just swimsuits, it was already hard enough to get neutrally buoyant in the pool without wetsuit. Now we had to not only do our skills in much colder water but also have totally different buoyancy profile. In addition, water is pretty murky there, so that is another new factor to consider. We had to do 4 dives, 2 on Saturday and 2 on Sunday.

But first 2 dives really pushed me exhausted me and I woke up on Sunday with low grade fever. I would have been fine if I had taken some Advil but with COVID19 in the news and just didn’t wanted to push myself, I didn’t go.

Then lockdown happened. So I could not do my last 2 dives until June.

Scuba International was really nice about it, I thought I had to pay for gear rental this time but the loaned me the gear for free again. Also I had prepaid for Sunday entry at Scuba Ranch, but they mailed me a raincheck. So I was able to my last 2 dives for the same cost as if I had not missed my dives initially.

This time water temperature was about 80F. It is amazing how big of difference 20F is, we dived in just swimsuits, no need of wetsuit at all. Also skills were so much easier to do too. Water was still murky but it wasn’t as bad as I remembered from the first time.

I highly recommend that you do your Open Water Diver training during summer. And checkout Scuba International, they are awesome.


iPad Pro as main machine after 2 years

I got my iPad Pro at the end of 2017. Before buying it, I had read many blog posts by various developers who were using iPad for programming and web development. But soon after I bought it, I realized that serious web development on iPad is hard. The biggest issue was debugging JavaScript and CSS without web tools. At first, I was having buyer’s remorse but I loved the form factor of iPad and loved drawing on it. I am used to reading on Kindle and iPad was just too heavy for long reading sessions but it was very decent reading device for quick reading sessions. So I kept it.

Initially, iPad was fun device for infotainment. But slowly I started to become more productive on it. I stopped doing web or app development. Instead, switched to command-line based projects such as algorithmic trading or data science experiments. It was sort of subconscious change as I carry iPad around a lot more than my laptop and when I had iPad with me, I didn’t wanna build anything with UI.

Currently, I cannot get rid of my personal laptop completely because I use it for some dev projects, I was learning Flutter and been playing with Godot. I tried to setup Flutter on my VPS but I could never get it to work right. Also laptop is needed for various trading softwares like Wealth Lab Pro or Think or Swim. Wealth Lab Pro is what got me into algorithmic trading but unfortunately it is Windows only. However, I am using RDP to log into Windows machine from my iPad. It is not a smooth experience but doable.

Currently, I use following apps on iPad Pro:

  • Blink shell for ssh connections to my VPSes.
  • ia Writer for writing fiction.
  • Kindle app
  • Working Copy for working with my repos on github and bitbucket.
  • Apple Photos app
  • Procreate for drawing and painting
  • Affinity Photo for drawing and editing photos
  • Snapseed for editing photos
  • Apple Notes for quick notes with Pencil
  • Dropbox for transferring files between Windows machine, Android phone, and MacBook Pro
  • Microsoft Remote Desktop
  • And then usual entertainment apps such Netflix, YouTube, etc

Also I tend to avoid installing most apps and use websites, like Reddit or Facebook. I rather login to website instead of an app on my machine that is constantly monitoring and sending data to mothership.


More research on choosing dev stack for game dev

Last week, I had decided to use Swift/Apple’s ecosystem for initial gamedev. But I wasn’t feeling 100% okay with getting locked into Apple’s ecosystem.

So I spent last week doing more research on developing simple apps using Swift, Xamarin, Flutter, and React Native.

Since I use JavaScript at work, React Native would be the easiest way for me to get started but it feels too much like work and I am kind of tired of js/npm dependencies and build tools. One nice thing about staying in Apple’s ecosystem is that everything has really good documentation and feels more polished.

Then looking at Flutter, I love their docs and it looks very clean and polished. It also has game dev engines. It has a few game engines available.

And Xamarin, probably most mature cross-platform. The nice thing about Xamarin is that it uses C# which means my skills can transfer over to Unity. Xamarin also has game engines, good docs.

Idea

The first game idea that I am thinking is an app for project management, tasks, and relationships. As game dev is my side hustle, it is one of the lowest priority. After day job, I need to do errands, play with my son, and hangout with my wife. House projects such as painting walls are higher priorities. Then staying in touch with friends and families should be next priority.

But when I start a new project, I forget about everything and everyone. The most project management tools are build for teams working on commercial projects.

So the first project for me to build project management tool that is suitable for personal life and side-hustles. The few key features of this will be:

  • One time tasks - One time things like drop off packages at UPS.
  • Repetitive tasks - Such as take out trash
  • Each type of tasks can be part of a project. Project is basically just a label or category on a task.
  • Habits - Help you build or break habits.
  • Contacts - Name, number, social media profiles, birthdays
    • You can set a reminder to connect with your contacts every so often.
    • Add notes and photos for each contact
  • Reports or dashboard to show you your next highest priority tasks, who you need to contact, etc
  • Privacy - This will run locally, no data should be needed to stored on any server. Probably will use json format file for easy export or import of data from the app.
  • (Optional) Gamification - This might be simple as adding contacts or building new habits will earn you badges or level ups.