Showing posts with label slide window. Show all posts
Showing posts with label slide window. Show all posts

Sunday, April 9, 2017

Find string using slide window - a small talk

April 9, 2017

Introduction


It is exciting to write the sliding window search algorithm with time complexity O(N),  N is the string's length. The similar algorithm is here on geeksongeeks.com, and also it is very close to the Leetcode 76: Minimum Window Substring.

There is a short story about the sliding window algorithm. Julia still remembered that 2 years ago in 2015 January, Julia asked to get her first onsite interview after a tech talk social event, she could not pass phone screen from top four software companies, Facebook. But she likes to find out what if she has one onsite interview and what she should learn.

She was asked to solve the algorithm to search a minimum substring as the second algorithm, but she failed to solve the problem on onsite interview and she could not write any code with a lot of hints. This is the first onsite coding interview she managed to get in the city of Vancouver after working full time over 5 years.

After a week analysis of the algorithm, Julia decided to start to write a coding blog, practice coding every day.

A coding blog starting January 2015


The only way Julia can think about improving the algorithm and data structure problem solving is related to learn from her tennis sports practice in the city of Vancouver. What she did is to work on tennis sport practice over one hundred hours, two hundreds hours, and then she started to play double matches and met over hundred people on the tennis court.

She understood that onsite interview is such a great help for her to understand that she needs to make life style change. She needs to find those people working hard on algorithm and data structure practice, work on something together, practice together.

She likes to give back to others, shows her generous to share, most likely she will share her failure, struggle at the beginning.

She started to write day by day, now her coding blog is like a tree planted by the water that sends out its roots by the stream (Jerimiah 17:8).

Here is the blog about the algorithm to find minimum substring using sliding window technique written 2 years ago, January 2015. This is the time Julia understood that it is important for her to start to write a coding blog to help herself. She felt so frustrated on the onsite interview but she quickly learned something related to her tennis sports practice.

This time Julia came out the idea in less than 1 minute, but she still needs to work on a few implementation details.


Code review and study 


Julia wrote 30 minutes about an algorithm to search a string using slide window in the mock interview. The code has some issues and she could not finish the algorithm. First she likes to code review her algorithm.

C# code is here at the practice, it took 30 minutes to write.

Will work on code more after the practice, here is C# version - revision 1.
Will add some test case to make sure the code is perfect.

4/9/2017
Added a test case, debugged the code and found a bug, C# version - revision 2.
line 72 - line 103 - code smells, duplicate logic in if/ else both cases.

4/10/2017 10:28pm
Continue to make code more clean, readable. The code smells in revision 2. Move left pointer loop standalone. C# version - revision 3.

6/30/2017
Fix the bug in the code, add a few lines of code 98 - 101. The C# code is here.

Code Review 


C# code is here at the practice.

Highlights of good things and bad things in the code written in mock interview 30 minutes:

1. line 2 - 19 writing of algorithm analysis is very good.
2. line 2 - 19 missing the slide window left point move forward design - skip more than one char
3. line 63 - 65 - this is a bug, for example, unique string "xyz", slide window "xyyz", if next char is x, then "yzx" will be shortest. It is a bug to reset start and end pointer.
4. line 74 - 76 - if statement should be a while loop
    need to add checking whether minimum string is found or not.

Final version after mock interview experience is here. C# version - revision 3.

Fully understand the test case first


In order to write good and working code, Julia had to force herself to work on a test case first next time. Here is the test case she worked on April 11, 2017, a few days after mock interview experience.

Work on the simple test case again and again, write down the analysis here (4/11/2017):

Find string using sliding window

xyz     xyyzx

Iterate the string one char a time
x
xy
xyy
xyyz
xyyzx

When to move left pointer? skip two chars in a row - "xy"

xyyzx -> yyzx, remove left pointer, skip x 
yyzx -> yzx,     remove left pointer, skip y

Do one thing a time. Every iteration, add the visited char to the slide window, add char to the slide window if it is new, otherwise increase the count.  Check left pointer to see if it can move forward, make sure do a loop, sometimes it can skip multiple chars. Check if slide window contains a string including all unique characters.  

Actionable Items


1. Study the discussion of Leetcode 78.



On the other hand, seeing you find your way out of a difficult situation tells a lot about your character, how you perform under pressure, your ability to think on your feet and your problem solving skills.

1. Not thinking about an algorithm

Make things simpler for yourself. Write down an example on the board and think about just solving that particular instance of the problem by hand.

Small test case -> generalize it back into an algorithm form. 

Julia, please validate the argument. Sounds like true to Julia in 2017.
People tend to bomb their first few sets of interviews. This is mostly because they don’t have sufficient practice with how to handle that pressure of solving an unknown question.

15 mock interview - systematic way
 

Actionable Items


Related blog in Chinese - sliding window algorithm, link is here. 

Follow up 


June 29, 2017

Mock practice again, C# code is here.

Need to write some test case and make sure that the code is working.


Tuesday, May 24, 2016

LeetCode 159: Longest Substring with At Most Two Distinct Characters

May 24, 2016

Work on the algorithm. The string "eoeab", the longest substring with at most two distinct characters is "eoe", and the length is 3.

1. Read the blog about solution:

http://yuanhsh.iteye.com/blog/2188917

Brute force solution:  O(n^3)

Sliding window  - better solution O(n) solution in time complexity

2. Study the code:

https://github.com/jianminchen/LeetCode-Java-Solutions/blob/master/159.longest-substring-with-at-most-two-distinct-characters.java

Write C# code:
https://gist.github.com/jianminchen/9061c12fee5e050e56a98cb3ffcc6f57





Thursday, April 28, 2016

HackerRank: Bear And Steady Gene - binary search algorithm (VI)

April 28, 2016

Previous blog on binary search on Bear and Gene algorithm:

Come back to the problem on binary search solution, figure out the design:


Problem statement:

https://www.hackerrank.com/contests/hourrank-6/challenges/bear-and-steady-gene  

A gene is represented as a string of length  (where  is divisible by ), composed of the letters , , , and . It is considered to be steady if each of the four letters occurs exactly  times. For example,  and are both steady genes.

Study code using binary search:

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

https://gist.github.com/jianminchen/395eb9e76fe19cc9338f

Comment:
Binary search is better than linear search using two pointers.

Brute force O(n^2) -> linear search O(n) -> Binary search O(logn) <- Not True!

Java code:
https://gist.github.com/jianminchen/d01faa03ca9b06696db3
C# code
https://gist.github.com/jianminchen/76dffc51880a80279f25

First, go through two test cases: "GTTCCAAA" and "GAAATTCC"

1. "GTTCCAAA",

Binary search is doing this way:
Biggest value of search string length is 8.
First, divide range from 0 to 8 into half, 4
Find first string with length 4,
one is "GTTC", one is "CAAA",
and then, remove count of first half, rest string (two parts, seperated) "CAAA", since A is repeated 3 times, not in the range;
instead of stopping, wrongly conclude that 4 is not high value, go through all the possible substring with length 4, by sliding window of search string: "GTTC" forward from left to right, but keep the same window size
"GTTC" -> "TTCC"->"TCCA"->stop here, since "TCCA" is removed from counting of GENES="ACGT", fit into the requirement.

Next, low=0, high=4, mid = 2,

Because both test cases with one 'A' to replace, Julia figured out through the debugging:

The slide window of fixed length technique,
How to slide?
Which direction to slide?

Kind of clever in design.
Time complexity analysis: length search using binary search, n - length of string, O(log n) times; each search for length m, go over each string once, since using calculated counting array, only do add one/ remove one at a time, one char only does the work once. So, it is O(n) on this.

Total time complexity: O(n logn)
Conclusion: this binary search is not better than linear search is previous blog (IV). 

Thursday, July 16, 2015

leetcode: longest substring without repeating characters

July 16, 2015 

Problem statement: 

Longest Substring Without Repeating Characters



Read the blog:


这算法写了很多次, 时间太长, 半年前, 有一次写了二个小时, 写不下去, 想法不好, 没有办法收场; 接着, 又写了四天, 每天二小时, 把上次代码拿出来看, 有什么问题, 改写.  过后想, 这样学习, 时间是浪费的, 打的是疲劳站; 工作中没有这么复杂的问题, 解决问题, 一定要评估复杂程度.

改变学习方式, 看以上的网页, 看Java的代码, 改写C#; 然后, 增加一些测试的内容, 帮助自己记忆算法的主要思想, 然后, 再改写; 用最简化的测试案例手工检测代码. 二三个小时搞定, 比半年前写的C#简单很多.

关键是用别人的想法, 又加快改写代码的速度, 改写后的代码更方便自己记忆. 这算法用移动窗口, 所以, 在代码中定义窗口起点, 长度, 什么时候决定更新窗口起点; 用一个数组(256字符)记录每个字符上次所在的位置, 然后, 对当前点, 窗口最右点, 判断是在窗口中出现没有; 间接判断, 看上次的位置在滑动窗口外还是里面.

学习别人的代码, 又练习自己改写代码, 写测试的内容, 多练习总是有新的体会.

Julia发现改写代码, 从其他语言到C#, 让她有机会快速练习写代码, 学习C#语言; 同时, 体会和其他语言的不同, 开阔眼界; 读的再多, 想法很好, 不会写代码实现, 或超过时间范围, 或写起来头痛, 太多错误, 都通过Leetcode训练, 有所提高. 

Share C# code:


First blog about the same problem:

http://juliachencoding.blogspot.ca/2015/06/longest-substring-without-repeating.html

"撑死胆大的,饿死胆小的. ", 虽然是个歇后语, 但是, 这道题目, 如果只考虑抽象思维, Hashset, 不具体讨论256字符等具体内容, 确实可以10 - 15分钟写出代码. 这是Julia练习的代码, 在第一次训练几个月之后. 

https://github.com/jianminchen/Leetcode_C-/blob/master/3LongestSubstringWithoutRepeating.cs