Thursday, August 11, 2016

LeetCode [360] Sort Transformed Array

LeetCode [359] Logger Rate Limiter

359. Logger Rate Limiter
Easy

Design a logger system that receive stream of messages along with its timestamps, each message should be printed if and only if it is not printed in the last 10 seconds.

Given a message and a timestamp (in seconds granularity), return true if the message should be printed in the given timestamp, otherwise returns false.

It is possible that several messages arrive roughly at the same time.

Example:

Logger logger = new Logger();

// logging string "foo" at timestamp 1
logger.shouldPrintMessage(1, "foo"); returns true; 

// logging string "bar" at timestamp 2
logger.shouldPrintMessage(2,"bar"); returns true;

// logging string "foo" at timestamp 3
logger.shouldPrintMessage(3,"foo"); returns false;

// logging string "bar" at timestamp 8
logger.shouldPrintMessage(8,"bar"); returns false;

// logging string "foo" at timestamp 10
logger.shouldPrintMessage(10,"foo"); returns false;

// logging string "foo" at timestamp 11 

logger.shouldPrintMessage(11,"foo"); returns true; 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Logger {
    Map<String, Integer> map;

    /** Initialize your data structure here. */
    public Logger() {
        map = new HashMap<>();
    }
    
    /** Returns true if the message should be printed in the given timestamp, otherwise returns false.
        If this method returns false, the message will not be printed.
        The timestamp is in seconds granularity. */
    public boolean shouldPrintMessage(int timestamp, String message) {
        if(map.isEmpty() || !map.containsKey(message) || timestamp-map.get(message)+1>10){
            map.put(message, timestamp);
            return true;
        }else{
            return false;
        }
    }
}

/**
 * Your Logger object will be instantiated and called as such:
 * Logger obj = new Logger();
 * boolean param_1 = obj.shouldPrintMessage(timestamp,message);
 */

LeetCode [358] Rearrange String k Distance Apart

Given a non-empty string s and an integer k, rearrange the string such that the same characters are at least distance k from each other.
All input strings are given in lowercase letters. If it is not possible to rearrange the string, return an empty string "".
Example 1:
Input: s = "aabbcc", k = 3
Output: "abcabc" 
Explanation: The same letters are at least distance 3 from each other.
Example 2:
Input: s = "aaabc", k = 3
Output: "" 
Explanation: It is not possible to rearrange the string.
Example 3:
Input: s = "aaadbbcc", k = 2
Output: "abacabcd"
Explanation: The same letters are at least distance 2 from each other.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class Solution {
public:
    //find the next valid char can be pus at "index"
    int getChar(vector<int>& counts, vector<int>& valid, int index)
    {
        int m = 0, offset = -1;
        for(int i=0; i<26; ++i)
        {
            if(counts[i]>m && index>=valid[i])
            {
                m = counts[i];//greedy: use the char with max count
                offset = i;
            }
        }
        return offset;
    }

    string rearrangeString(string s, int k) {
        if(k==0) return s;
        int n = s.size();
        vector<int> counts(26, 0);//counts[i] is count of char('a'+i) 
        vector<int> valid(26, 0);//valid[i] is the next smallest valid position of char('a'+i)
        for(auto c:s) counts[c-'a']++;

        string ret;
        for(int i=0; i<n; ++i)
        {
            int offset = getChar(counts, valid, i);
            if(offset<0) return "";//cannot find a valid char
            ret += ('a'+offset);
            counts[offset]--;
            valid[offset] = i+k;
        }
        return ret;
    }
};

LeetCode [357] Count Numbers with Unique Digits

LeetCode [355] Design Twitter

LeetCode [354] Russian Doll Envelopes

LeetCode [353] Design Snake Game

Design a Snake game that is played on a device with screen size = width x heightPlay the game online if you are not familiar with the game.
The snake is initially positioned at the top left corner (0,0) with length = 1 unit.
You are given a list of food's positions in row-column order. When a snake eats the food, its length and the game's score both increase by 1.
Each food appears one by one on the screen. For example, the second food will not appear until the first food was eaten by the snake.
When a food does appear on the screen, it is guaranteed that it will not appear on a block occupied by the snake.
Example:
Given width = 3, height = 2, and food = [[1,2],[0,1]].

Snake snake = new Snake(width, height, food);

Initially the snake appears at position (0,0) and the food at (1,2).

|S| | |
| | |F|

snake.move("R"); -> Returns 0

| |S| |
| | |F|

snake.move("D"); -> Returns 0

| | | |
| |S|F|

snake.move("R"); -> Returns 1 (Snake eats the first food and right after that, the second food appears at (0,1) )

| |F| |
| |S|S|

snake.move("U"); -> Returns 1

| |F|S|
| | |S|

snake.move("L"); -> Returns 2 (Snake eats the second food)

| |S|S|
| | |S|

snake.move("U"); -> Returns -1 (Game over because snake collides with border)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
class SnakeGame
{
    set<pair<int, int>> hist;    //keep the coordinates of the current snake. used to decide if the snake eats itself
    deque<pair<int, int>> snake; //also keep the snake coordinates. used to update the snake body after each movement
    vector<vector<int>> food;
    int pos; //store the food position
    int w, h;

  public:
    /** Initialize your data structure here.
        @param width - screen width
        @param height - screen height 
        @param food - A list of food positions
        E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]. */
    SnakeGame(int width, int height, vector<vector<int>> &food)
    {
        w = width;
        h = height;
        pos = 0;
        this->food = food;
        pair<int, int> p = make_pair(0, 0);
        snake.push_front(p);
        hist.insert(p);
    }

    /** Moves the snake.
        @param direction - 'U' = Up, 'L' = Left, 'R' = Right, 'D' = Down 
        @return The game's score after the move. Return -1 if game over. 
        Game over when snake crosses the screen boundary or bites its body. */
    int move(string direction)
    {
        pair<int, int> tail = snake.back();
        pair<int, int> head = snake.front();

        //remove the tail
        snake.pop_back();
        hist.erase(tail);

        if (direction == "U")
            head.first--;
        if (direction == "L")
            head.second--;
        if (direction == "R")
            head.second++;
        if (direction == "D")
            head.first++;

        //game over
        if (head.first < 0 || head.first >= h || head.second < 0 || head.second >= w || hist.count(head))
            return -1;

        //add new head
        snake.push_front(head);
        hist.insert(head);

        //no more food. score is the snake size minus the original size 1
        if (pos == food.size())
            return snake.size() - 1;

        //extend the snake body by adding the tail back
        if (head.first == food[pos][0] && head.second == food[pos][1])
        {
            snake.push_back(tail);
            hist.insert(tail);
            pos++;
        }

        return snake.size() - 1;
    }
};

/**
 * Your SnakeGame object will be instantiated and called as such:
 * SnakeGame* obj = new SnakeGame(width, height, food);
 * int param_1 = obj->move(direction);
 */
class SnakeGame {
    int foodIndex = 0;
    Set<Integer> hist = new HashSet<>();
    Deque<Integer> body = new LinkedList<>();
    int w, h;
    int[][] food;

    /** Initialize your data structure here.
        @param width - screen width
        @param height - screen height 
        @param food - A list of food positions
        E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]. */
    public SnakeGame(int width, int height, int[][] food) {
        w = width;
        h = height;
        this.food = food;
        body.add(0);
    }
    
    /** Moves the snake.
        @param direction - 'U' = Up, 'L' = Left, 'R' = Right, 'D' = Down 
        @return The game's score after the move. Return -1 if game over. 
        Game over when snake crosses the screen boundary or bites its body. */
    public int move(String direction) {
        int head = body.peekFirst();
        int tail = body.peekLast();

        //remove tail
        body.removeLast();
        hist.remove(tail);

        int i = head/w, j = head%w;
        if(direction.equals("U")) i--;
        if(direction.equals("D")) i++;
        if(direction.equals("L")) j--;
        if(direction.equals("R")) j++;
        int newPostion = i*w+j;

        //game over
        if(i<0 || i>=h || j<0 || j>=w || hist.contains(newPostion)) return -1;

        //add new head
        body.addFirst(newPostion);
        hist.add(newPostion);

        //no more food, score is body size -1
        if(foodIndex == food.length) return body.size()-1;

        //eat food, body length increases by 1 to the end
        if(i==food[foodIndex][0] && j==food[foodIndex][1]){
            body.add(tail);
            hist.add(tail);
            foodIndex++;
        }

        return body.size()-1;
    }
}

/**
 * Your SnakeGame object will be instantiated and called as such:
 * SnakeGame obj = new SnakeGame(width, height, food);
 * int param_1 = obj.move(direction);
 */

LeetCode [352] Data Stream as Disjoint Intervals

LeetCode [351] Android Unlock Patterns

 351. Android Unlock Patterns

Medium

Given an Android 3x3 key lock screen and two integers m and n, where 1 ≤ m ≤ n ≤ 9, count the total number of unlock patterns of the Android lock screen, which consist of minimum of m keys and maximum n keys.

 

Rules for a valid pattern:

  1. Each pattern must connect at least m keys and at most n keys.
  2. All the keys must be distinct.
  3. If the line connecting two consecutive keys in the pattern passes through any other keys, the other keys must have previously selected in the pattern. No jumps through non selected key is allowed.
  4. The order of keys used matters.

 

 

Explanation:

| 1 | 2 | 3 |
| 4 | 5 | 6 |
| 7 | 8 | 9 |

Invalid move: 4 - 1 - 3 - 6
Line 1 - 3 passes through key 2 which had not been selected in the pattern.

Invalid move: 4 - 1 - 9 - 2
Line 1 - 9 passes through key 5 which had not been selected in the pattern.

Valid move: 2 - 4 - 1 - 3 - 6
Line 1 - 3 is valid because it passes through key 2, which had been selected in the pattern

Valid move: 6 - 5 - 4 - 1 - 9 - 2
Line 1 - 9 is valid because it passes through key 5, which had been selected in the pattern.

 

Example:

Input: m = 1, n = 1
Output: 9
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
public class Solution {
    // cur: the current position
    // remain: the steps remaining
    int DFS(boolean vis[], int[][] skip, int cur, int remain) {
        if(remain < 0) return 0;
        if(remain == 0) return 1;
        vis[cur] = true;
        int rst = 0;
        for(int i = 1; i <= 9; ++i) {
            // If vis[i] is not visited and (two numbers are adjacent or skip number is already visited)
            if(!vis[i] && (skip[cur][i] == 0 || (vis[skip[cur][i]]))) {
                rst += DFS(vis, skip, i, remain - 1);
            }
        }
        vis[cur] = false;
        return rst;
    }
    
    public int numberOfPatterns(int m, int n) {
        // Skip array represents number to skip between two pairs
        int skip[][] = new int[10][10];
        skip[1][3] = skip[3][1] = 2;
        skip[1][7] = skip[7][1] = 4;
        skip[3][9] = skip[9][3] = 6;
        skip[7][9] = skip[9][7] = 8;
        skip[1][9] = skip[9][1] = skip[2][8] = skip[8][2] = skip[3][7] = skip[7][3] = skip[4][6] = skip[6][4] = 5;
        boolean vis[] = new boolean[10];
        int rst = 0;
        // DFS search each length from m to n
        for(int i = m; i <= n; ++i) {
            rst += DFS(vis, skip, 1, i - 1) * 4;    // 1, 3, 7, 9 are symmetric
            rst += DFS(vis, skip, 2, i - 1) * 4;    // 2, 4, 6, 8 are symmetric
            rst += DFS(vis, skip, 5, i - 1);        // 5
        }
        return rst;
    }
}