Showing posts with label linked list. Show all posts
Showing posts with label linked list. Show all posts

Tuesday, May 15, 2018

Swap kth node with kth to last node in singly linked list (recursive solution)

May 15, 2018


Introduction


I had a mock interview this morning. I learned such important lesson in mock interview. Actually I tried to reconstruct a linked list involving four nodes in the linked list. Actually I can just swap values in those two nodes instead.

After the mock interview I also learned the lesson to write a recursive solution. Since I can write the algorithm in less than 10 minutes.

Mock interview


Here is the transcript at 8:00 AM mock interview.

Recursive solution


Here is my C# practice after the mock interview.

Tuesday, November 7, 2017

Divide to n small linked list with length difference at most one

Nov. 7, 2017

Introduction


It is the first time I went through a friend met in mock interview, we both worked on the same algorithm together. I wrote two version of code, one is recursive function, one is iterative one.

Problem statement can be written in the following:

Given a Linked list, split it into x number of smaller linked list where the size difference between any two list should be at most 1


Algorithm practice


It is so interesting to have discussion with the peer outside mock interview platform. I always think like a math major graduate student, the first 5 minutes I will go over anything including mathematics, and then I rested all time. Since I went through the linked list practice in 2016, here is one of linked list practice blog to document my practice. 

I like to observe how the peer picked up the analysis and worked hard on the coding. For me, it is just another routine and I do not need to think about too much. 

C# code is written here, and later on I will compile and add some test cases. 

First, I wrote a recursive solution. The link is here. And then I wrote an iterative solution, the link is here

Also, I like to give the code review for the peer's code. The code is here


Statistics


Time spent in discussion 7:15 pm - 9:18 pm 



Thursday, June 2, 2016

Leetcode 146: LRU cache - a practice makes difference (II)

June 2, 2016


Previous blog:

Warm up the algorithm: (a lot of hurdles to go through)

Questions and answers:

How to design LRU? Data structure? What for?

LRU

One of the most common cache systems is LRU (least recently used). In fact, another common interview question is to discuss data structures and design of an LRU cache. Let’s start with this approach.
The way LRU cache works is quite simple. When the client requests resource A, it happens as follow:
  • If A exists in the cache, we just return immediately.
  • If not and the cache has extra storage slots, we fetch resource A and return to the client. In addition, insert A into the cache.
  • If the cache is full, we kick out the resource that is least recently used and replace it with resource A.
The strategy here is to maximum the chance that the requesting resource exists in the cache. So how can we implement a simple LRU?


LRU design

An LRU cache should support the operations: lookup, insert and delete. Apparently, in order to achieve fast lookup, we need to use hash. By the same token, if we want to make insert/delete fast, something like linked list should come to your mind. Since we need to locate the least recently used item efficiently, we need something in order like queue, stack or sorted array.
To combine all these analyses, we can use queue implemented by a doubly linked list to store all the resources. Also, a hash table with resource identifier as key and address of the corresponding queue node as value is needed.
Here’s how it works. when resource A is requested, we check the hash table to see if A exists in the cache. If exists, we can immediately locate the corresponding queue node and return the resource. If not, we’ll add A into the cache. If there are enough space, we just add a to the end of the queue and update the hash table. Otherwise, we need to delete the least recently used entry. To do that, we can easily remove the head of the queue and the corresponding entry from the hash table.


Eviction policy

When the cache is full, we need to remove existing items for new resources. In fact, deleting the least recently used item is just one of the most common approaches. So are there other ways to do that?
As mentioned above, The strategy is to maximum the chance that the requesting resource exists in the cache. I’ll briefly mention several approaches here:
  • Random Replacement (RR) – As the term suggests, we can just randomly delete an entry.
  • Least frequently used (LFU) – We keep the count of how frequent each item is requested and delete the one least frequently used.
  • W-TinyLFU – I’d also like to talk about this modern eviction policy. In a nutshell, the problem of LFU is that sometimes an item is only used frequently in the past, but LFU will still keep this item for a long while. W-TinyLFU solves this problem by calculating frequency within a time window. It also has various optimizations of storage.
Skip concurrency and distributed cache in this design. 
Next, talk about coding part - data structure and algorithm using her own words:

C# implementation. 

int capacity - specify the size of cache, cache should be with limited size, since resource is limited, specially for high speed access. source code on line 24.

int size - current size of cache - track current size of cache to determine  if eviction is needed or not.
source code on line 24.

Design a double linked list, so ListNode class is defined with two pointers, prev, next
source code from line 10 - line 22.

every entry has key, value. Use int to simplify the coding. Source code, line 12.
line 12   public int key, val; 

Also, we need to add two more variables: dummy head, dummy tail to help maintain the double linked list. source code on line 25.

Also, we need to be able to find the key in O(1) since it is in cache. Extra space is used, maintain a hash map using Dictionary class in C#:
line 27    Dictionary(int key, ListNode)

Let us count how many variables inside the class LRUCache:
6 variables:    - memorize the variable count - 6 - Try to recall. 

private int capacity, size; 
private ListNode dummyHead, dummyTail; 
private Dictionary<int, ListNode> map; 

ListNode class as a node in a double linked list: 
 public int key, value; 
 publie ListNode prev, next; 

4 variables. 

Statistics: 
Time spent: 2 hours +

Research paper:    feel so good to read a research paper after some coding 

Reading blog: (June 30, 2016)

Monday, May 9, 2016

Compare two linked list

May 9, 2016

Problem statement:
https://www.hackerrank.com/challenges/compare-two-linked-lists

Compare two linked list:
https://gist.github.com/jianminchen/904a955b78a56ece032f5b9a681f91fc

Submission code to study:
https://www.hackerrank.com/challenges/compare-two-linked-lists/leaderboard

Iterative solution:
https://goo.gl/vyGJkW








Merge two sorted linked list

May 9, 2016
Problem statement:
https://www.hackerrank.com/challenges/merge-two-sorted-linked-lists

Merge two sorted linked list
https://gist.github.com/jianminchen/c09df676896e938d7f6c3819e301545c


Reverse a doubly linked list:

May 9, 2016

Problem statement:
https://www.hackerrank.com/challenges/reverse-a-doubly-linked-list

Reverse a doubly linked list:
https://gist.github.com/jianminchen/5bdf999c91964e87788e0d010eb52e53


Linked List: print list

More practice on May 9, 2016
Linked List on HackerRank:
problem statements:
https://www.hackerrank.com/domains/data-structures/linked-lists/difficulty/all/page/1



print list
https://gist.github.com/jianminchen/cd219738d812605e0c6ced926d2e488c

Insert a node at tail of a linked list

More practice on May 9, 2016
Linked List on HackerRank:
problem statements:
https://www.hackerrank.com/domains/data-structures/linked-lists/difficulty/all/page/1


Insert a node at tail of a linked list
https://gist.github.com/jianminchen/957d2025fd310a9e59fb88fe8766e0de


Insert a node at the head of a linked list

More practice on May 9, 2016
Linked List on HackerRank:
problem statements:
https://www.hackerrank.com/domains/data-structures/linked-lists/difficulty/all/page/1



Insert a node at the head of a linked list
https://gist.github.com/jianminchen/79dd121f3135769d57088c7d2e9e51fe


Insert a node at a specific position in a linked list

More practice on May 9, 2016
Linked List on HackerRank:
problem statements:
https://www.hackerrank.com/domains/data-structures/linked-lists/difficulty/all/page/1


Insert a node at a specific position:
https://gist.github.com/jianminchen/5b357be38d6bad427e885c7b7343c19b


Linked List: Delete a node

More practice on May 9, 2016
Linked List on HackerRank:
problem statements:
https://www.hackerrank.com/domains/data-structures/linked-lists/difficulty/all/page/1


Delete a node:
https://gist.github.com/jianminchen/d0a360f5a5a4be3b6d94e09d6bd0f266


Reverse a linked list

More practice on May 9, 2016
Linked List on HackerRank:
problem statements:
https://www.hackerrank.com/domains/data-structures/linked-lists/difficulty/all/page/1

Reverse a linked list:
https://gist.github.com/jianminchen/2c0203cebd076ae329a10e870c414219


HackerRank: Linked List - Get Node value

More practice on May 9, 2016
Linked List on HackerRank:
problem statements:
https://www.hackerrank.com/domains/data-structures/linked-lists/difficulty/all/page/1

Get Node value:
https://gist.github.com/jianminchen/d4da2ec82876d93bcd1920927054702d


Sunday, May 8, 2016

HackerRank: Insert a node in a double linked list

May 8, 2016


Problem statement:
https://www.hackerrank.com/challenges/insert-a-node-into-a-sorted-doubly-linked-list


Julia spent over 30 minutes to work out a solution:

https://gist.github.com/jianminchen/a9794202ddc66d25cc1d416e04adc7a9

A few of mistakes in first writing:
1. If the list is empty, add a new node, forget to return the node;
2. Insert a node, 3 possible positions:
   before the head,
   in the middle of list,
   at the end of list <-  edge case -> forget the edge case first time

Review other submissions:

Question and answer:

1. What do you learn through the study?

Julia learns to write an iterative solution for the problem. And also she fixed all the bugs and then complete the task.

The solution Julia takes is not the best one, she uses dummy head node to help, and then, use iterative solution to the do work. Need more practice.

She learned that she needs more ideas, in order to complete it in less than 10 minutes.

Also, the linked list - the simple problem is also very helpful to learn how to think recursively.

2. This is a solution to study - use recursive function, much short code, less time to write:

https://gist.github.com/jianminchen/e1e528eda506c185182a68a0df3be544

Before Julia reads the code in detail, she wrote her own recursive solution. It is fast, no dummy head need, and also much easy to read:

https://gist.github.com/jianminchen/fc0d0fc2171ed891330d5cf773c45206

Forget to add one more line: after line 30, before line 31.
(head->next)->prev=head;

Let us talk about the idea using recursive function - how to design the function? 

Test case: 2->4->6, insert a value 1, 

First, deal with the case that the list is empty: create a new node, and then return;
Second, if the inserted value is less than head's value, then create a new head with value 1, 
link it to the head; 
Otherwise, the first node is processed, and the next node of it is the value of recursive call. 
It saves time to write recursively here.


3. What are the common issues you find in the submissions?

https://www.hackerrank.com/challenges/insert-a-node-into-a-sorted-doubly-linked-list/leaderboard

--
More practice on May 9, 2016
Linked List on HackerRank:
problem statements:
https://www.hackerrank.com/domains/data-structures/linked-lists/difficulty/all/page/1

Get Node value:
https://gist.github.com/jianminchen/d4da2ec82876d93bcd1920927054702d

Reverse a doubly linked list:
https://gist.github.com/jianminchen/5bdf999c91964e87788e0d010eb52e53

Merge two sorted linked list
https://gist.github.com/jianminchen/c09df676896e938d7f6c3819e301545c

Compare two linked list:
https://gist.github.com/jianminchen/904a955b78a56ece032f5b9a681f91fc

Reverse a linked list:
https://gist.github.com/jianminchen/2c0203cebd076ae329a10e870c414219

Reverse print:
https://gist.github.com/jianminchen/91e8dfeac0e962307b30f4afd0bb6f98

Delete a node:
https://gist.github.com/jianminchen/d0a360f5a5a4be3b6d94e09d6bd0f266

Insert a node at a specific position:
https://gist.github.com/jianminchen/5b357be38d6bad427e885c7b7343c19b

Insert a node at the head of a linked list
https://gist.github.com/jianminchen/79dd121f3135769d57088c7d2e9e51fe

Insert a node at tail of a linked list
https://gist.github.com/jianminchen/957d2025fd310a9e59fb88fe8766e0de

print list
https://gist.github.com/jianminchen/cd219738d812605e0c6ced926d2e488c

Trees:
Problem statements:
https://www.hackerrank.com/domains/data-structures/trees

height of tree:
https://gist.github.com/jianminchen/18de7257b29bf6ccbab63cdc93d4077f

Top view:
problem statement:
https://www.hackerrank.com/challenges/tree-top-view
https://gist.github.com/jianminchen/f7742a123f3524c1d0fbd98e71c8f516

Level Order Traversal:
https://gist.github.com/jianminchen/a3194f885fc542a7f5827cbcdc92a3f5

HackerRank: Linked List - Find Merge Point of two linked list

May 8, 2016

Problem statement:
https://www.hackerrank.com/challenges/find-the-merge-point-of-two-joined-linked-lists

Cpp solution:

https://gist.github.com/jianminchen/ce99505020ee58f2fd23ecd78bb2f19f

Value simple, easy question, solve the problem, learn from other submissions. From the simple ones, build up skills, feel more comfortable to solve moderate, difficult one later.

Submissions:
https://www.hackerrank.com/challenges/find-the-merge-point-of-two-joined-linked-lists/leaderboard

Julia's favorite code:
1. define a few functions, very well written:
length, position, common - use recursive function, very short function - 3 lines of code each function
https://gist.github.com/jianminchen/2ab387360a0ff2ef41c10c67219fd1c1
source:
https://goo.gl/J5WK7y

2. unbelievable short - only use for loop to do things:
https://gist.github.com/jianminchen/9d14ff515146af193c4bee660b0a6fb8

Question and answer:
1. What do you learn through the problem solving? Code submission study?

Julia likes to document the problems she found when she reads first 100 solutions, in order to improve the speed, accuracy, and avoid bugs - avoid repetition of same logic:

1. Best code she found so far:
https://gist.github.com/jianminchen/2ab387360a0ff2ef41c10c67219fd1c1

2. One is to use brute force, go through each node in the first list, compare to each node in the second list; The algorithm is not optimal.

3. Shortest time to write the code, in less than 20 lines:
https://gist.github.com/jianminchen/9d14ff515146af193c4bee660b0a6fb8

3. Repeat same code twice - if/else statement - avoid two cases, simplify to one case.

4. Same code as Julia does, but better code:
https://goo.gl/NXTurm