Category Archives: Leetcode

1269. Number of Ways to Stay in the Same Place After Some Steps

You have a pointer at index 0 in an array of size arrLen. At each step, you can move 1 position to the left, 1 position to the right in the array or stay in the same place  (The pointer should not be placed outside the array at any time).

Given two integers steps and arrLen, return the number of ways such that your pointer still at index 0 after exactly steps steps.

Since the answer may be too large, return it modulo 10^9 + 7.

 

Example 1:

Input:

 steps = 3, arrLen = 2

Output:

 4

Explanation:

There are 4 differents ways to stay at index 0 after 3 steps.
Right, Left, Stay
Stay, Right, Left
Right, Stay, Left
Stay, Stay, Stay

Example 2:

Input:

 steps = 2, arrLen = 4

Output:

 2

Explanation:

 There are 2 differents ways to stay at index 0 after 2 steps
Right, Left
Stay, Stay

Example 3:

Input:

 steps = 4, arrLen = 2

Output:

 8

 

Constraints:

  • 1 <= steps <= 500
  • 1 <= arrLen <= 10^6

 

class Solution {
    public int numWays(int steps, int arrLen) {
        int end = Math.min(steps, arrLen);
        
        int mod = 1000000000 + 7;
        long[][] dp = new long[steps+1][end+5];
        
        dp[0][0] = 1;
        
        for (int i = 0; i < steps; i++) {
            dp[i+1][0] = (dp[i][0] + dp[i][1]) % mod;
            for (int j = 1; j < end; j++) {
                dp[i+1][j] = (dp[i][j-1] + dp[i][j] + dp[i][j+1]) % mod;
            }
        }
        return (int) (dp[steps][0]);
    }
}

 

1268. Search Suggestions System

Given an array of strings products and a string searchWord. We want to design a system that suggests at most three product names from products after each character of searchWord is typed. Suggested products should have common prefix with the searchWord. If there are more than three products with a common prefix return the three lexicographically minimums products.

Return list of lists of the suggested products after each character of searchWord is typed.

 

Example 1:

Input:

 products = ["mobile","mouse","moneypot","monitor","mousepad"], searchWord = "mouse"

Output:

 [
["mobile","moneypot","monitor"],
["mobile","moneypot","monitor"],
["mouse","mousepad"],
["mouse","mousepad"],
["mouse","mousepad"]
]

Explanation:

 products sorted lexicographically = ["mobile","moneypot","monitor","mouse","mousepad"]
After typing m and mo all products match and we show user ["mobile","moneypot","monitor"]
After typing mou, mous and mouse the system suggests ["mouse","mousepad"]

Example 2:

Input:

 products = ["havana"], searchWord = "havana"

Output:

 [["havana"],["havana"],["havana"],["havana"],["havana"],["havana"]]

Example 3:

Input:

 products = ["bags","baggage","banner","box","cloths"], searchWord = "bags"

Output:

 [["baggage","bags","banner"],["baggage","bags","banner"],["baggage","bags"],["bags"]]

Example 4:

Input:

 products = ["havana"], searchWord = "tatiana"

Output:

 [[],[],[],[],[],[],[]]

 

Constraints:

  • 1 <= products.length <= 1000
  • 1 <= Σ products[i].length <= 2 * 10^4
  • All characters of products[i] are lower-case English letters.
  • 1 <= searchWord.length <= 1000
  • All characters of searchWord are lower-case English letters.
class Solution {
    public List<List<String>> suggestedProducts(String[] products, String searchWord) {
        
        List<List<String>> r = new ArrayList<>();
        Arrays.sort(products);

        for (int i = 0; i < searchWord.length(); i ++){
            List<String> rr = new ArrayList<>();
            String prefix = searchWord.substring(0,i+1);

            for (int j = 0; j < products.length && rr.size() < 3; j ++){
                if(products[j].startsWith(prefix)){
                    rr.add(products[j]);
                }
            }

            r.add (rr);
        }
        return r;
    }
}

 

Yes, we can introduce trie for more results. 3 is fairly small here

1267. Count Servers that Communicate

You are given a map of a server center, represented as a m * n integer matrix grid, where 1 means that on that cell there is a server and 0 means that it is no server. Two servers are said to communicate if they are on the same row or on the same column.

Return the number of servers that communicate with any other server.

 

Example 1:

Input:

 grid = [[1,0],[0,1]]

Output:

 0
Explanation: No servers can communicate with others.

Example 2:

Input:

 grid = [[1,0],[1,1]]

Output:

 3
Explanation: All three servers can communicate with at least one other server.

Example 3:

Input:

 grid = [[1,1,0,0],[0,0,1,0],[0,0,1,0],[0,0,0,1]]

Output:

 4
Explanation: The two servers in the first row can communicate with each other. The two servers in the third column can communicate with each other. The server at right bottom corner can't communicate with any other server.

 

Constraints:

  • m == grid.length
  • n == grid[i].length
  • 1 <= m <= 250
  • 1 <= n <= 250
  • grid[i][j] == 0 or 1
class Solution {
    public int countServers(int[][] grid) {
        int result = 0 ;
        int[] a = new int[grid.length];
        int[] b = new int[grid[0].length];
        
        for (int i = 0; i < grid.length; i ++){
            for (int j = 0; j < grid[0].length; j ++){
                if (grid[i][j] == 1){
                    a[i] ++;
                    b[j] ++;
                    result ++;
                }
            }
        }
        
        for (int i = 0; i < grid.length; i ++){
            for (int j = 0; j < grid[0].length; j ++){
                if (a[i] == 1 && b[j] == 1 && grid[i][j] == 1){
                    result --;
                }
            }
        }
        
        return result;
    }
    
}

 

1266. Minimum Time Visiting All Points

On a plane there are n points with integer coordinates points[i] = [xi, yi]. Your task is to find the minimum time in seconds to visit all points.

You can move according to the next rules:

  • In one second always you can either move vertically, horizontally by one unit or diagonally (it means to move one unit vertically and one unit horizontally in one second).
  • You have to visit the points in the same order as they appear in the array.

 

Example 1:

Input:

 points = [[1,1],[3,4],[-1,0]]

Output:

 7

Explanation:

One optimal path is

[1,1]

 -> [2,2] -> [3,3] ->

[3,4]

-> [2,3] -> [1,2] -> [0,1] ->

[-1,0]

   
Time from [1,1] to [3,4] = 3 seconds 
Time from [3,4] to [-1,0] = 4 seconds
Total time = 7 seconds

Example 2:

Input:

 points = [[3,2],[-2,2]]

Output:

 5

 

Constraints:

  • points.length == n
  • 1 <= n <= 100
  • points[i].length == 2
  • -1000 <= points[i][0], points[i][1] <= 1000

 

class Solution {
    public int minTimeToVisitAllPoints(int[][] points) {
        int result = 0;
        int prev_x = points[0][0];
        int prev_y = points[0][1];
        for (int i = 1; i < points.length; i ++){
            int x = points[i][0];
            int y = points[i][1];
            
            int diff_x = Math.abs(x - prev_x);
            int diff_y = Math.abs(y - prev_y);
            
            result += Math.min(diff_x,diff_y)+Math.abs(diff_x-diff_y);
            
            prev_x = x;
            prev_y = y;
        }
        return result;
    }
}

 

1161. Maximum Level Sum of a Binary Tree

Given the root of a binary tree, the level of its root is 1, the level of its children is 2, and so on.

Return the smallest level X such that the sum of all the values of nodes at level X is maximal.

 

Example 1:

Input:

[1,7,0,7,-8,null,null]

Output:

2

Explanation:

Level 1 sum = 1.
Level 2 sum = 7 + 0 = 7.
Level 3 sum = 7 + -8 = -1.
So we return the level with the maximum sum which is level 2.

 

Note:

  1. The number of nodes in the given tree is between 1 and 10^4.
  2. -10^5 <= node.val <= 10^5

 

Another “Follow your heart” question.

I’m using level order traversal (BFS) here.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int maxLevelSum(TreeNode root) {
        Queue<TreeNode> q = new LinkedList<>();
        q.add(root);
        int max = 0;
        int lv = 1;
        
        int max_lv = 0;
        
        while (! q.isEmpty()){
            
            int size = q.size();
            int level_sum = 0;
            for (int i = 0; i < size; i ++){
                TreeNode cur = q.poll();
                if(cur.left != null)
                    q.add(cur.left);
                if (cur.right != null)
                    q.add(cur.right);
                level_sum += cur.val;
            }
            if (level_sum > max){
                max = level_sum;
                max_lv = lv;
            }
            lv ++;
            
        }
        return max_lv;
    }
    
    
}

 

904. Fruit Into Baskets

In a row of trees, the i-th tree produces fruit with type tree[i].

You start at any tree of your choice, then repeatedly perform the following steps:

  1. Add one piece of fruit from this tree to your baskets.  If you cannot, stop.
  2. Move to the next tree to the right of the current tree.  If there is no tree to the right, stop.

Note that you do not have any choice after the initial choice of starting tree: you must perform step 1, then step 2, then back to step 1, then step 2, and so on until you stop.

You have two baskets, and each basket can carry any quantity of fruit, but you want each basket to only carry one type of fruit each.

What is the total amount of fruit you can collect with this procedure?

 

Example 1:

Input:

[1,2,1]

Output:

3

Explanation:

We can collect [1,2,1].

Example 2:

Input:

[0,1,2,2]

Output:

3

Explanation:

We can collect [1,2,2].
If we started at the first tree, we would only collect [0, 1].

Example 3:

Input:

[1,2,3,2,2]

Output:

4

Explanation:

We can collect [2,3,2,2].
If we started at the first tree, we would only collect [1, 2].

Example 4:

Input:

[3,3,3,1,2,1,1,2,3,3,4]

Output:

5

Explanation:

We can collect [1,2,1,1,2].
If we started at the first tree or the eighth tree, we would only collect 4 fruits.

 

Note:

  1. 1 <= tree.length <= 40000
  2. 0 <= tree[i] < tree.length

First Draft.

Code is accepted, but the quality is a JOKE.

class Solution {
    public int totalFruit(int[] tree) {
        
        if (tree.length <= 2){
            return tree.length;
        }
        
        int max = 2;
        int cur_max = 2;
        
        int a = tree[0];
        int b = tree[1];
        
        int a_last_index = 0;
        Integer b_last_index = null;
        
        boolean a_is_eldest = true;
        
        // get the second <Unique> number
        for(int i = 1; i < tree.length; i ++){
            if (tree[i] != a){
                b = tree[i];
                b_last_index = i;
                break;
            } else {
                // And we have to update last index of a as well
                cur_max ++;
                a_last_index = i;
                a_is_eldest = false;
            }
        }
        // update max here
        max = Math.max(max, cur_max);
        
        // if only single unique number in the array...
        if (b_last_index == null){
            return tree.length;
        }
        
        
        // Scan from the right of the second unique number
        for(int i = b_last_index+1; i < tree.length; i ++){
            int cur = tree[i];
            
            if(cur == a){

                cur_max ++;
                a_last_index = i;
                a_is_eldest = false;

            } else if (cur == b){

                cur_max ++;
                b_last_index = i;
                a_is_eldest = true;

            } else {

                // Third unique number appeared!
                // Remove eldest, and reduce current max to the last occurance of the number to be removed.
                if(a_is_eldest){
                    cur_max = i - a_last_index;
                    a = cur;
                    a_last_index = i;
                    a_is_eldest = false;
                } else {
                    cur_max = i - b_last_index;
                    b = cur;
                    b_last_index = i;
                    a_is_eldest = true;
                }
            }
            max = Math.max(max, cur_max);
        }
        return max;
    }
}

 

Code after refactoring:

class Solution {
    public int totalFruit(int[] tree) {
        
        if (tree.length <= 2){
            return tree.length;
        }
        
        int max = 2;
        int cur_max = 1;
        
        int a = tree[0];
        int a_last_index = 0;
        
        Integer b = null;
        Integer b_last_index = null;
        
        boolean a_is_eldest = true;
    
        
        for(int i = 1; i < tree.length; i ++){
            int cur = tree[i];
            
            if(cur == a){
                cur_max ++;
                a_last_index = i;
                a_is_eldest = false;
                
            } else if (b == null || cur == b) {
                
                if(b == null){
                    b = cur;
                }
                cur_max ++;
                b_last_index = i;
                a_is_eldest = true;
                
            } else {

                if(a_is_eldest){
                    cur_max = i - a_last_index;
                    a = cur;
                    a_last_index = i;
                    a_is_eldest = false;
                } else {
                    cur_max = i - b_last_index;
                    b = cur;
                    b_last_index = i;
                    a_is_eldest = true;
                }

            }
            max = Math.max(max, cur_max);
        }
        return max;
    }
}

 

There could be more things for refactoring, putting that aside, can we use any data structure?

Maybe LinkedHashMap<Type, LastSeenIndex> in access order mode?  it’s an overkill for ‘collecting two types’,  but could be useful for 3 or more types.

 

Starting by copy & paste from LRUCache. I added a variable to save the value of the most recent removed entry. The value of it is updated before the eldest entry is removed.

 

The modified LRUCache

class LRUCache extends LinkedHashMap<Integer, Integer>{
    private int capacity;

    // Save the latest index of the recent removed item.
    int index_removed = 0;
    
    public LRUCache(int capacity) {
        super(capacity, 0.75F, true);
        this.capacity = capacity;
    }

    public int get(int key) {
        return super.getOrDefault(key, -1);
    }

    public void put(int key, int value) {
        super.put(key, value);
    }

    @Override
    protected boolean removeEldestEntry(Map.Entry<Integer, Integer> eldest) {

        // If the eldest has to be removed, save it's value (most recent index)
        if(size() > capacity){
            index_removed = eldest.getValue();
        }

        return size() > capacity; 
    }
}

 

Then, update the main function… and combine them

 

class Solution {

    public static final int TYPES_ALLOWED = 2;
 
    public int totalFruit(int[] tree) {
        
        if (tree.length <= TYPES_ALLOWED){
            return tree.length;
        }
        
        int cur_max = 1;
        int max = 1;
        
        // For a follow-up of more than 2 types is allowed.. just change the number here
        LRUCache map = new LRUCache(TYPES_ALLOWED);
    
        map.put(tree[0], 0);
        
        for(int i = 1; i < tree.length; i ++){
            int cur = tree[i];
            if (map.get(cur) != -1 || map.size() < 2){
                cur_max ++;
                map.put(cur, i);
            } else {
                map.put(cur, i);
                cur_max = i - map.index_removed;
            }
            
            max = Math.max(max, cur_max);
            
        }
        return max;
    }
}

class LRUCache extends LinkedHashMap<Integer, Integer>{
    private int capacity;
    int index_removed = 0;
    
    public LRUCache(int capacity) {
        super(capacity, 0.75F, true);
        this.capacity = capacity;
    }

    public int get(int key) {
        return super.getOrDefault(key, -1);
    }

    public void put(int key, int value) {
        super.put(key, value);
    }

    @Override
    protected boolean removeEldestEntry(Map.Entry<Integer, Integer> eldest) {
        if(size() > capacity){
            index_removed = eldest.getValue();
        }
        return size() > capacity; 
    }
}

Time complexity. O(n). basically going through all elements once (n),  times LRUCache O(1).

This is basically a sliding window solution, while the Map is used for maintaining the valid window status.

Well, we can also use other Collections, giving the accepted types is two. The search and insertion time have to be counted after the number of accepted types is increased. So a Hash* will have a better performance.

 

Can we use a LinkedHashSet? Yes, then giving the type to be removed, find the closest index before the current index.

 

973. K Closest Points to Origin

We have a list of points on the plane.  Find the K closest points to the origin (0, 0).

(Here, the distance between two points on a plane is the Euclidean distance.)

You may return the answer in any order.  The answer is guaranteed to be unique (except for the order that it is in.)

 

Example 1:

Input:

points = [[1,3],[-2,2]], K = 1

Output:

[[-2,2]]

Explanation:

The distance between (1, 3) and the origin is sqrt(10).
The distance between (-2, 2) and the origin is sqrt(8).
Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin.
We only want the closest K = 1 points from the origin, so the answer is just [[-2,2]].

Example 2:

Input:

points = [[3,3],[5,-1],[-2,4]], K = 2

Output:

[[3,3],[-2,4]]
(The answer [[-2,4],[3,3]] would also be accepted.)

 

Note:

  1. 1 <= K <= points.length <= 10000
  2. -10000 < points[i][0] < 10000
  3. -10000 < points[i][1] < 10000
A acceptable but definitely no the best solution….
In PHP:
  1. a ** b means power (a,b)
  2.  <=>, the spaceship operator,  used by ‘comparator’
    1. if left < right return -1
    2. if left > right return 1
    3. if left == right return 0
class Solution {

    /**
     * @param Integer[][] $points
     * @param Integer $K
     * @return Integer[][]
     */
    function kClosest($points, $K) {
        usort($points, function ($a, $b){
            return ($a[0]**2 + $a[1]**2) <=> ($b[0]**2 + $b[1]**2);
        });
        
        $result = [];
        $i = 0;
        foreach($points as $p){
            if($i >= $K){
                break;   
            }
            $result[] = $p;
            $i ++;
    
        }
        return $result;
    }
}

 

102. Binary Tree Level Order Traversal

Given a binary tree, return the level order traversal of its nodes’ values. (ie, from left to right, level by level).

For example:
Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its level order traversal as:

[
  [3],
  [9,20],
  [15,7]
]

Straight forward solution:
root node in => left and right children out . -- Lv1
lv 1 nodes in => lv 2 nodes out......
until no more next lv.
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     public $val = null;
 *     public $left = null;
 *     public $right = null;
 *     function __construct($value) { $this->val = $value; }
 * }
 */
class Solution {

    /**
     * @param TreeNode $root
     * @return Integer[][]
     */
    function levelOrder($root) {
        $q = [];
        $result = [];
        
        if($root === null){
            return $result;
        }
        $q[] = $root;
        while (count($q) > 0){
            $current_level = [];
            $current_result = [];
            foreach ($q as $node){
                if ($node->left !== null) 
                    $current_level[] = $node->left;
                
                $current_result[] = $node->val;
                
                if ($node->right !== null) 
                    $current_level[] = $node->right;
            }
            $q = $current_level;
            $result [] = $current_result;
        }

        return $result;
    }
}
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> r = new ArrayList<>();
        
        if(root == null){
            return r;
        }
        
        Queue<TreeNode> q = new LinkedList<>();
        q.add(root);
        
        while(!q.isEmpty()){
            
            int sizeSnapshot = q.size();
            List<Integer> current_level = new ArrayList<>();
            
            
            for(int i = 0; i < sizeSnapshot; i ++){
                TreeNode t = q.poll();
                if(t.left != null){
                    q.add(t.left);
                }
                
                current_level.add(t.val);
                
                if(t.right != null){
                    q.add(t.right);
                }
            }
            r.add(current_level);
        }
        
        return r;
    }
}