Showing posts with label leetcode. Show all posts
Showing posts with label leetcode. Show all posts

Dec 23, 2020

[python3] list vs. deque performance

Question [lc 1032]:
Implement the StreamChecker class as follows:
StreamChecker(words): Constructor, init the data structure with the given words.
query(letter): returns true if and only if for some k >= 1,
the last k characters queried (in order from oldest to newest, including this letter just queried)
spell one of the words in the given list.

Example:

StreamChecker streamChecker = new StreamChecker(["cd","f","kl"]); // init the dictionary.
streamChecker.query('a'); // return false
streamChecker.query('b'); // return false
streamChecker.query('c'); // return false
streamChecker.query('d'); // return true, because 'cd' is in the wordlist
streamChecker.query('e'); // return false
streamChecker.query('f'); // return true, because 'f' is in the wordlist
streamChecker.query('g'); // return false
streamChecker.query('h'); // return false
streamChecker.query('i'); // return false
streamChecker.query('j'); // return false
streamChecker.query('k'); // return false
streamChecker.query('l'); // return true, because 'kl' is in the wordlist

Note:
1 <= words.length <= 2000
1 <= words[i].length <= 2000
Words will only consist of lowercase English letters.
Queries will only consist of lowercase English letters.
The number of queries is at most 40000.

Solve:
It's a trie problem. The thought should focus on query.
Thoughts:
  • How to preserve the previous input state?
    stack
  • Could backtrace be faster?
    Yes, only if the words last character being input could consider a hit.
    Thus should build a reverse trie.
  • Tests can up to thousands thus query would be called about that much, Thus the stack used to preserve records could be large enough to trigger a realloc, which is SLOW(copy existing values to new memory address). In Python, instead of using list(which act like C++ vector), use deque to prevent realloc system call. Ref: https://stackoverflow.com/a/23487658


from collections import deque

class StreamChecker:
    def __init__(self, words: List[str]):
        self.trie = {}
        self.stack = deque()

        for word in set(words):
            node = self.trie

            for c in word[::-1]:
                if c not  in node:
                    node[c] = {}
                node = node[c]

            node[None] = None

    def query(self, letter: str) -> bool:
        self.stack.appendleft(letter)

        node = self.trie

        for c in self.stack:
            if None in node:
                return True

            if c not in node:
                return False
            node = node[c]

        return None in node

Jul 4, 2018

[algorithm][data structure] KD Tree

[algorithm][data structure] Quad Tree

// C++ Implementation of Quad Tree
#include <iostream>
#include <cmath>
using namespace std;
 
// Used to hold details of a point
struct Point
{
    int x;
    int y;
    Point(int _x, int _y)
    {
        x = _x;
        y = _y;
    }
    Point()
    {
        x = 0;
        y = 0;
    }
};
 
// The objects that we want stored in the quadtree
struct Node
{
    Point pos;
    int data;
    Node(Point _pos, int _data)
    {
        pos = _pos;
        data = _data;
    }
    Node()
    {
        data = 0;
    }
};
 
// The main quadtree class
class Quad
{
    // Hold details of the boundary of this node
    Point topLeft;
    Point botRight;
 
    // Contains details of node
    Node *n;
 
    // Children of this tree
    Quad *topLeftTree;
    Quad *topRightTree;
    Quad *botLeftTree;
    Quad *botRightTree;
 
public:
    Quad()
    {
        topLeft = Point(0, 0);
        botRight = Point(0, 0);
        n = NULL;
        topLeftTree  = NULL;
        topRightTree = NULL;
        botLeftTree  = NULL;
        botRightTree = NULL;
    }
    Quad(Point topL, Point botR)
    {
        n = NULL;
        topLeftTree  = NULL;
        topRightTree = NULL;
        botLeftTree  = NULL;
        botRightTree = NULL;
        topLeft = topL;
        botRight = botR;
    }
    void insert(Node*);
    Node* search(Point);
    bool inBoundary(Point);
};
 
// Insert a node into the quadtree
void Quad::insert(Node *node)
{
    if (node == NULL)
        return;
 
    // Current quad cannot contain it
    if (!inBoundary(node->pos))
        return;
 
    // We are at a quad of unit area
    // We cannot subdivide this quad further
    if (abs(topLeft.x - botRight.x) <= 1 &&
        abs(topLeft.y - botRight.y) <= 1)
    {
        if (n == NULL)
            n = node;
        return;
    }
 
    if ((topLeft.x + botRight.x) / 2 >= node->pos.x)
    {
        // Indicates topLeftTree
        if ((topLeft.y + botRight.y) / 2 >= node->pos.y)
        {
            if (topLeftTree == NULL)
                topLeftTree = new Quad(
                    Point(topLeft.x, topLeft.y),
                    Point((topLeft.x + botRight.x) / 2,
                        (topLeft.y + botRight.y) / 2));
            topLeftTree->insert(node);
        }
 
        // Indicates botLeftTree
        else
        {
            if (botLeftTree == NULL)
                botLeftTree = new Quad(
                    Point(topLeft.x,
                        (topLeft.y + botRight.y) / 2),
                    Point((topLeft.x + botRight.x) / 2,
                        botRight.y));
            botLeftTree->insert(node);
        }
    }
    else
    {
        // Indicates topRightTree
        if ((topLeft.y + botRight.y) / 2 >= node->pos.y)
        {
            if (topRightTree == NULL)
                topRightTree = new Quad(
                    Point((topLeft.x + botRight.x) / 2,
                        topLeft.y),
                    Point(botRight.x,
                        (topLeft.y + botRight.y) / 2));
            topRightTree->insert(node);
        }
 
        // Indicates botRightTree
        else
        {
            if (botRightTree == NULL)
                botRightTree = new Quad(
                    Point((topLeft.x + botRight.x) / 2,
                        (topLeft.y + botRight.y) / 2),
                    Point(botRight.x, botRight.y));
            botRightTree->insert(node);
        }
    }
}
 
// Find a node in a quadtree
Node* Quad::search(Point p)
{
    // Current quad cannot contain it
    if (!inBoundary(p))
        return NULL;
 
    // We are at a quad of unit length
    // We cannot subdivide this quad further
    if (n != NULL)
        return n;
 
    if ((topLeft.x + botRight.x) / 2 >= p.x)
    {
        // Indicates topLeftTree
        if ((topLeft.y + botRight.y) / 2 >= p.y)
        {
            if (topLeftTree == NULL)
                return NULL;
            return topLeftTree->search(p);
        }
 
        // Indicates botLeftTree
        else
        {
            if (botLeftTree == NULL)
                return NULL;
            return botLeftTree->search(p);
        }
    }
    else
    {
        // Indicates topRightTree
        if ((topLeft.y + botRight.y) / 2 >= p.y)
        {
            if (topRightTree == NULL)
                return NULL;
            return topRightTree->search(p);
        }
 
        // Indicates botRightTree
        else
        {
            if (botRightTree == NULL)
                return NULL;
            return botRightTree->search(p);
        }
    }
};
 
// Check if current quadtree contains the point
bool Quad::inBoundary(Point p)
{
    return (p.x >= topLeft.x &&
        p.x <= botRight.x &&
        p.y >= topLeft.y &&
        p.y <= botRight.y);
}
 
// Driver program
int main()
{
    Quad center(Point(0, 0), Point(8, 8));
    Node a(Point(1, 1), 1);
    Node b(Point(2, 5), 2);
    Node c(Point(7, 6), 3);
    center.insert(&a);
    center.insert(&b);
    center.insert(&c);
    cout << "Node a: " <<
        center.search(Point(1, 1))->data << "\n";
    cout << "Node b: " <<
        center.search(Point(2, 5))->data << "\n";
    cout << "Node c: " <<
        center.search(Point(7, 6))->data << "\n";
    cout << "Non-existing node: "
        << center.search(Point(5, 5));
    return 0;
}

May 19, 2018

[algorithm][dp][leetcode] Dynamic programming thinking

Reference:
[algorithm][DP] thinking steps
Erik Demaine - Dynamic Programming I: Fibonacci, Shortest Paths

Reading note for:
Nikola Otasevic - Dynamic Programming – 7 Steps to Solve any DP Interview Problem

  1. Spot if it's a DP problem
    1. Breaking it down into a collection of simpler subproblems.
    2. Solving each of those subproblems just once,
    3. and storing their solutions.

    The next time the same subproblem occurs, instead of recomputing its solution, one simply looks up the previously computed solution.

    This saves computation time at the expense of a modest expenditure in storage space.
    Whether the problem solution can be expressed as a function of solutions to similar smaller problems.
  2. Identify problem variables
    Established that there is some recursive structure between our subproblems.

    Need to express the problem in terms of the function parameters and see which of those parameters are changing.

    Typically in interviews, you will have one or two changing parameters, but technically this could be any number.
     i.e Question: Compute edit distance between strings

    Counting the number of changing parameters is valuable to determine the number of subproblems we have to solve
    , but it is also important in its own right in helping us strengthen the understanding of the recurrence relation from step 1.
  3. Clearly express the recurrence relation
    Don't rush into implementation.

    Expressing the recurrence relation as clearly as possible will strengthen your problem understanding and make everything else significantly easier.

    Once figuring out that the recurrence relation exists and specify the problems in terms of parameters, this should come as a natural step.

    Think:
    How do problems relate to each other? In other words, let's assume that you have computed the subproblems. How would you compute the main problem?
  4. Identify the base cases
    (重要!)
    A base case is a subproblem that doesn't depend on any other subproblem.
    (Like FP's ending point/ C++ variadic template)

    In order to find such subproblems,
    1. try a few examples, see how problem simplifies into smaller subproblems,
    2. and at what point it cannot be simplified further.

    The reason a problem cannot be simplified further is that one of the parameters would become a value that is not possible given 'constraints' of a problem.

    It can be a little challenging to convert assertions that we make about parameters into programmable base cases.

    This is because, in addition to listing the assertions if want to make code look concise and not check for unnecessary conditions, we need to also think about which of these conditions are even possible.
  5. Decide if you want to implement it iteratively or recursively
    i.e (stack overflow consideration, tail call)

    In both approaches, you would have to determine the recurrence relation and the base cases.

    trade-offs:



    Stack overflow issues are typically a deal breaker and a reason why would not want to have recursion in a (backend) production system.

    However, for the purposes of the interview, as long as mentioning the trade-offs, we should typically be fine with either of the implementations.
    Should feel comfortable implementing both.
  6. Add memoization
    Used for storing the results of expensive function calls and returning the cached result when the same inputs occur again.

    Why are we adding memoization to our recursion? We encounter the same subproblems which without memoization are computed repeatedly.
    Those repetitions very often lead to exponential time complexities.

    In recursive solutions, adding memoization should feel straightforward.
    Remember that memoization is just a cache of the function results. There are times when you want to deviate from this definition in order to squeeze out some minor optimizations, but treating memoization as a function result cache is the most intuitive way to implement it.

    i.e
    1. Store function result into your memory before every return statement

    2. Look up the memory for the function result before start doing any other computation
  7. Determine Time complexity
    Count the number of states
        This will depend on the number of changing parameters in the problem

    Think about the work done per each state.
         i.e if everything else but one state has been computed, how much work do we have to do to compute that last state

May 6, 2018

[algorithm][DP] thinking steps


  1. Define subproblems : count number of subproblems
  2. Guess(part of solution)  (fib doesn't need to guess, it's specific)
  3. Relate subproblems solutions(with recursion) (想出其中的關聯)
  4. Recurse & memoize OR buttom up approach(for loop). (must be asyclic, DAG, thus can use toposort.)
  5. Solve original problem (確定真的解決原本的問題)

Supplement article: Tail call

Apr 19, 2018

[LC] bst to double linked list

bst <-> double linked list.
straight.
class Solution(object):
    def bst_llst(self, root):

        def dfs(root):
            """
            :param root: Node
            :ret: (min, max)
                    9

                 6        14

              3    8|  12
                 /
                7

            """

            if not root:
                return

            lmin = lmax = rmin = rmax = None

            if root.left:
                lmin, lmax = dfs(root.left)
                lmax.right = root
                root.left = lmax

            if root.right:
                rmin, rmax = dfs(root.right)
                root.right = rmin
                rmin.left = root

            if not lmin:
                lmin = root
            if not rmax:
                rmax = root

            return lmin, rmax

        mmin, mmax = dfs(root)

        mmin.left = mmax
        mmax.right = mmin
        return mmin

Apr 10, 2018

[LC][programming][algorithm] tilde operator

https://stackoverflow.com/questions/8305199/the-tilde-operator-in-python


def is_palindromic(s):
    return all(s[i] == s[~i] for i in range(len(s) / 2)) 
LC48:
class Solution:
    def rotate(self, A):
        n = len(A)
        for i in range(n/2):
            for j in range(n-n/2):
                A[i][j], A[~j][i], A[~i][~j], A[j][~i] = \
                         A[~j][i], A[~i][~j], A[j][~i], A[i][j]


LC: 246
class Solution(object):
    def isStrobogrammatic(self, num):
        """
        :type num: str
        :rtype: bool
        0 0  不能為第一個.
        1 1
        6 9
        9 6
        8 8
        """
        from __builtin__ import xrange

        dmap = dict((('0', '0'), ('1', '1'), ('6', '9'),
                     ('9', '6'), ('8', '8')))

        if num[0] == '0' and len(num) > 1:
            return False

        if len(num) % 2:
            # corner cases
            if num[len(num) / 2] not in ('0', '1', '8'):
                return False

        for i in xrange(len(num) / 2):
            if num[i] not in dmap or num[~i] != dmap[num[i]]:
                return False

        return True

Feb 7, 2016

[C++] [STL] vector.insert cache affinity concern.

Blog post:
Microsoft’s vector::insert is slower than it should be

Reference:
http://en.cppreference.com/w/cpp/container/vector/insert

The blog post is not really anything special but did a research on
cache affinity with vector.insert.

The author was fascinated by MS's implementation of
vector.insert with PRValue, which uses 3 reverse function call.

The trick has been mentioned in the book(thus i don't see any 'wow' factor out of it):
Programming Pearls(2nd edition) Ch. 2 Section 3, P.14 while ago.
And it honors cache locality if the range of data fits into the cache.

The author also brought up using
memmove
to do the rotation.

The memmove() function shall copy n bytes from the object pointed to by s2 into the object pointed to by s1. 
Copying takes place as if the n bytes from the object pointed to by s2 are first copied into a temporary array of n bytes that does not overlap the objects pointed to by s1 and s2, and 
then the n bytes from the temporary array are copied into the object pointed to by s1.

That is, memmove needs an extra temporary space. And not cache locality friendly if data range is too large.

Will look into Folly's implementation later this week.

Reference:

Sep 19, 2014

[leet] Reverse Stack without using extra memory

#include <iostream>
#include <stack>
#include <utility>

using namespace std;

template<typename STACK, typename T>
void pop(STACK&& stk, T&& val)
{
    if(stk.size() != 0)
    {
        auto tmp = stk.top();
        stk.pop();
        pop(stk, std::forward<T>(val));
        stk.push(tmp);
    }
    else
    {
        stk.push(std::forward<T>(val));
    }
}

template<typename STACK>
void reverse(STACK&& stk)
{
    if (stk.size() != 0)
    {
        auto tmp = stk.top();
        stk.pop();
        reverse(stk);
        pop(stk, tmp);
    }
}

int main()
{
    stack<int> stk;
    stk.push(1);
    stk.push(2);
    stk.push(3);
    stk.push(4);
    reverse(stk);
    cout << stk.top() << endl;
    stk.pop();
    cout << stk.top() << endl;
    stk.pop();
    cout << stk.top() << endl;
    stk.pop();
    cout << stk.top() << endl;
    stk.pop();
}