Showing posts sorted by relevance for query Leetcode 239. Sort by date Show all posts
Showing posts sorted by relevance for query Leetcode 239. Sort by date Show all posts

Thursday, September 14, 2017

July 18, 2017 algorithm review

Sept. 14, 2017


Introduction


It is two months ago, I did spend 3 to 4 hours to review my own practice before 8:00 pm. I went over around 30 algorithms, print one by one on the paper, and then read one by one. I really learned from the preparation, and I like to open a folder on my own github, and list all those algorithms I chose to study on July 18, 2017.

It is so interested to know that once I am busy with the study, the nervousness is kind of going away. I did very good one on preparation, and I had great performance later on the evening to complete code in limited time.

Algorithms


Algorithm 1. In order successor
Algorithm 2. Flatten the dictionary
Algorithm 3: HTree
Algorithm 4: Reverse words
Algorithm 5. Find distance binary tree
Algorithm 6. Leetcode 23 Merge K Sorted List
Algorithm 7: Leetcode 37 Sudoku
Algorithm 8: Leetcode 49 Group anagrams
Algorithm 9: Leetcode54 SpiralMatrix
Algorithm 10: Leetcode 72 Edit distance
Algorithm 11: Leetcode 114 Flatten Binary Tee to Linked List
Algorithm 12: Leetcode 212 Word Search II
Algorithm 13: Leetcode 295 Find median for path stream
Algorithm 14: Leetcode 295 median of stream
Algorithm 15. Leetcode 300 Longest Increasing Subsequence
Algorithm 16. Leetcode 416 Partition equal subset sum
Algorithm 17: Leetcode 516 Longest palindrome subsequence
Algorithm 18: Leetcode 605 Can place flowers
Algorithm 19: Binary tree two path same value
Algorithm 20: Leetcode 239 Sliding window maximum
Algorithm 21: Leetcode 57   Insert interval
Algorithm 22: Leetcode 10   Regular expression matching
Algorithm 23: Leetcode 547 Find Circle
Algorithm 24: Leetcode 130 Surrouned region
Algorithm 25: Maze Project
Algorithm 26: Short Job First using Icomparer
Algorithm 27: Leetcode 554 Brick wall



Wednesday, June 7, 2017

Leetcode 239: Sliding window maximum

June 7, 2017

Introduction


It is the third time to review Leetcode 239: Sliding window maximum. By searching the blog using Leetcode 239, Julia reviewed last two practices in 2015 and 2016. Here is the link.

This time Julia likes to go over Leetcode discussion on the algorithm, and then need to write down most important part - the analysis of using deque, the idea to prune the queue to make it minimum.

Algorithm talk


Julia's C# practice is here.

Read some discussions, take some notes for good comment:

The link is here.

We scan the array from 0 to n-1, keep "promising" elements in the deque. The algorithm is amortized O(n) as each element is put and polled once.

At each i, we keep "promising" elements, which are potentially max number in window [i-(k-1), i] or any subsequent window. This means if an element in the deque and it is out of i-(k-1), we discard them. We just need to poll from the head, as we are using a deque and elements are ordered as the sequence in the array.

Now only those elements within [i-(k-1),i] are in the deque. We then discard elements smaller than a[i] from the tail. This is because if a[x] < a[i] and x < i, then a[x] has no chance to be the "max" in [i-(k-1), i], or any other subsequent window: a[i] would always be a better candidate.

As a result elements in the deque are ordered in both sequence in array and their value. At each step the head of the deque is the max
element in [i-(k-1),i].

Another discussion link is here.

Keep indexes of good candidates in deque d. The indexes in d are from the current window, they're increasing, and their corresponding nums are decreasing. Then the first deque element is the index of the largest window value.

For each index i:

Pop (from the end) indexes of smaller elements (they'll be useless).
Append the current index.

Pop (from the front) the index i - k, if it's still in the deque (it falls out of the window).

If our window has reached size k, append the current window maximum to the output.

Follow up 


June 29, 2017
Work on a solution using SortedSet, C# code is here.

Thursday, September 13, 2018

Leetcode discuss

Sept. 13, 2018

Introduction

The following content is the copy of my page on github. The link is here. 
It takes a village to raise a child.
I like to adapt the culture to learn and contribute to Leetcode discuss community. It is so easy to learn from so many ideas, but it takes me more than 3 years five months to understand that I also should learn to contribute to the community.
I like to see if I adopt the value "It takes a village to raise a child", as a programmer, I think that in order to get smart, I have to learn to contribute Leetcode discuss. Since I find that it is so easy to learn the algorithm on leetcode discuss, I like to be one of them to work hard and share the thoughts and hard work.
This page is dedicated to show my effort to provide a feature to review all my past practice, all my sharing on Leetcode discuss.
It is time for me to share my practice on Leetcode.com discussion panel.
I like to encourage myself to share my code on Leetcode discussion. I learn so many things from those people sharing on Leetcode discussion panel. I like to be one of them.
Leetcode discuss
I will share more practice later. I also will add those links I shared before.
Sept. 9, 2018
Leetcode.com does not provide product feature to look up discuss shared by a player. Google search result will only show at most 20 results of my discuss.
Google search: Leetcode leetcode jianmin.chen.39
Here is the link.
Sept. 13, 2018
I like to list all my sharings on Tree easy level algorithms, Array easy level algorithms, Math easy level algorithms.
Tree easy level algorithms (solved 30)

Hard level (solved 33)

239. Sliding Window Maximum
optimal solution using LinkedList
My own blogs

Case study: leetcode 239 sliding window maximum

Sept. 13, 2018

Introduction


It is hard for me to get upvote on Leetcode.com discuss panel. I just started to share my code on Leetcode.com discuss starting from August 2018. I learned the lesson today since I was so surprised that I wrote the optimal solution more than three years ago by looking up Leetcode submission record.

It does not matter how many algorithms I practice, I have to learn to review what I have completed as well. Sometimes I may solve a hard level algorithm, I did one time on Leetcode 239 sliding window maximum more than three years ago.

Based on my analysis of this case related to the hard level algorithm, I decide to get more organized. It will be much more easy for me to review my past practice and find good ideas for each algorithm quickly.

My submission records


The optimal solution is buried in one of submissions, and it is the first time I reviewed it after three years.



I need to get more organized on my coding practice. 

Thursday, May 25, 2017

Coding Interviews - Harry He

May 25, 2017

Introduction


It is such a great book and Julia read the book back in 2015. Now it is the time to review the book again.

Book reading 


Question 69: Median of a stream (Julia's ranking:  10 out of 10  May 31, 2017)

Leetcode 295. Find median from data stream - discussion panel is here.

C# solution using SortedSet. The C# code to study is here.

C# solution using MinHeap/ MaxHeap - self defined. The study code is here.

Read blog about the discussion again - link is here - the blog on ardendertat.com



Question 85: binary tree is balanced? (Julia's ranking:  8 out of 10  May 31, 2017)


Algorithm 90: Given an array, check whether it contains a subset of numbers whose sum equals to 0

A little confused about solution discussed in the book, look up Google and then find this blog on geeksforgeeks:
Dyanmic programming / Set 25 ( Subset Sum Problem), recursive and also dynamic programmng solution.

Study leetcode 416: partition equal subset sum. The problem link is here.

Amazonian - USC alumni - Xie Tao - Leetcode profile is here.

Study the solution:
Java dynamic programming solution is here.

Study Leetcode 39: Combination Sum,
Julia's C# practice is here.

Leetcode 40 Combination Sum II.

Julia's C# practice is here.


Algorithm 93: Maximum in Queue

Leetcode 239 Sliding window maximum

Algorithm 98: Most profit from stock
June 8, 2017
Leetcode 121
Julia's C# practice is here. 

Leetcode 122
Julia's C# practice is here. 




Friday, June 30, 2017

C# SortedSet talk

June 30, 2017

It is a great idea to learn C# programming language using Leetcode. Julia searches Google using keyword "C# SortedSet Leetcode", and then she finds the following algorithms to work on:

Leetcode  23  Merge K Sorted Lists
Leetcode  57  Insert Intervals
Leetcode 128 Longest Consecutive Sequence
Leetcode 220 Remove Duplicate III
Leetcode 239 Sliding Window Maximum
Leetcode 295 Median of Streams


It takes a few hours to study those algorithm written using C# SortedSet.

Sunday, July 9, 2017

Am I good programmer?

July 9, 2017

Introduction


It is exciting to spend 30 minutes to do some research at the night of Sunday. The topic Julia chose is "Am I a good programmer?". Julia likes to be very competitive hackerrank contest player, good at computer algorithm and data structure. But also Julia likes to be a leader, enjoy the journey by sharing her struggle, learning process of hard topic on algorithm, data structure. How does she advance herself as a software programmer, learning as a system designer, and she also likes to pick up other skills. Like good humour, strong and healthy physical body and strong mental toughness, and good sense of humour, master a sports - tennis.

Julia made a few choices, chose to work on Leetcode algorithms, work on the coding blog, work on code review, Leetcode discussion. 


It is hard work to reinvent myself as a software programmer. Julia spends last 3 months to meet people and conduct mocking interview, in her career as a full time programmer last 7 year, it is the first time she starts to learn how to work with a peer through 60 minutes time range. She wrote a blog about common mistakes in mocking.

Last weekend Julia spent more than three hours to watch the show on netflix called Quantico, the actress Priyanka has more than 17.9M followers on twitter. Julia likes to spend some time to read how the actress develops skills and build a good connection with peers. The actor Jake wiki page is here.

Coding, learning algorithm, reading and also mocking, Julia starts to get good habit to practice daily. But it is better to take Sunday off . Say no to algorithm and data structure, mocking interviews on Sunday, learn to relax more in the summer. Also Julia has to spend time to work on the sponsor application project.

Julia still calculates how much time she spends on the internet in the week days, she did waste a lot of hours. Instead she should plan better to work on more meaningful activities, like attending Sunday church service, get connected to friends and family, play more sports like tennis single matches, make life more fun and exciting.


Study topic 



It is the great experience to serve 8000 views last month. Most of time the blog serves Julia very well, she has chance to keep tracking of her progress on algorithm and data structure, and also keep her motivated and focus very well. So far there are over 150,000 views on the blog.

Over 10 years ago, Julia spent over 3 months in 2006 to study how to apply teaching job but she never got too far. She remembered that the bible verse teaching about seeds, how to grow the confidence. Seed and soil, Matthew 13 - The Parable of the sower.


Julia spent whole month in the city of Canada, so 25% traffic is from Canada. In other words, Julia serves 75% traffic for other people while she enjoys her own blog with 1700 views. 



By integrating Leetcode with mocking interview algorithm, Julia also learns to serve other people, help herself as well to learn better on algorithm and data structure. Here is the list of Leetcode algorithms last 3 month Julia worked on. Also 30% of peers were happy to connect Julia on linkedin, total count is 33. 

The mocking interview totally changes the view of Linkedin, for a long time, Julia found out that she does not have time to get connected to people face-to-face, work on something together. 


Let us look in LinkedIn statistics and figure out something here as well. 


Julia spent time on mocking interview last 3 months, 90 mocking takes 90 hours; And Julia worked on related Leetcode algorithms more than 30 hours. She added 33 new Linkedin connections, total 201 views, 15% traffic is related to the new connections. 26 found you via Who Viewed Your Profile, in other words, Julia did some study on linkedIn profiles, 10% traffic is related to the activities. 75% traffic of 150 views are random traffic, Julia could not control and make some influence on it. 

Last 3 months Julia did not spend a lot of hours on code review. Here is her profile:


Julia found her most favorite website to study and get great ideas for algorithm, and learn C# programming, for example, C# class SortedSet is good to start. . It is called Leetcode discussion board. Here is Julia's profile on Leetcode discussion. 
A few issues needs to be addressed, but Julia will find time to solve them. 


Leetcode algorithms


Last 90 days, Julia worked on 52 leetcode algorithms. Here are the list:

52 Leetcode algorithms 

8, 10, 18,  23, 33,,37,,39, 44, 45, 47, 48, 54, 55, 57, 69, 72, 76, 78, 79, 114, 121, 122, 123, 128, 140, 151, 153, 189, 212, 220, 239, 295, 300, 416, 459, 480, 516, 551, 572, 575, 582, 591, 605, 606, 609



Sunday, February 13, 2022

【干货】刷题这样上手 面试必备的10个算法 | LeetCode清单 [下] DP需要学吗?面试小技巧分享

 Feb. 13, 2022

Here is the link. 

做这个视频 距离我上次刷题已经快两年了 我也是学了就忘那种 所以总结 复习和写文案都花了10个小时以上的时间 而且融合了我上百小时的刷题心血!! 而且我也不是擅长给讲题的那种 所以拍下来真的好累啊 感觉好多东西 我也不知道我有没有说清楚 哈哈哈哈 反正我脑汁已经没了 希望大家一定要点赞订阅!! 祝大家刷题加油 找工作顺利 都能拿到自己心仪的offer! ================================================== 以下是我说的 10 个算法和数据结构 和他们的 Leet Code 经典题! 功课都给你总结好了 还不来抄! 7. Pointer Manipulation a. 239. Sliding Window Maximum https://leetcode.com/problems/sliding... b. 3. Longest Substring Without Repeating Characters https://leetcode.com/problems/longest... c. 76. Minimum Window Substring https://leetcode.com/problems/minimum... 8. Sorting a. Time -- O(N log N) b. Merge Sort -- Space O(N) c. Quick Sort d. 148. Sort List https://leetcode.com/problems/sort-list/ 9. Convert Real Life Problem to Code a. 146. LRU Cache https://leetcode.com/problems/lru-cache/ b. 1066. Compus Bike https://leetcode.com/problems/campus-... c. 490. The Maze https://leetcode.com/problems/the-maze/ 10. Time Space Complexity a. 一般面试的时候 你说完算法 就要说 这个算法的 time / space complexity是什么 b. 每次你做完一道题 给自己养成一个习惯 就是想一下他的时间空间复杂度是多少



Thursday, September 13, 2018

Learn from my own practice

Sept. 13, 2018

Introduction


It is time for me to learn from my own practice on Leetcode.com. I have to get organized, make it much easy for me to review what my past practice. Here is the page I like to maintain called Leetcode discuss.

I read the submission of Leetcode 239 more than three years ago today, I was surprised that I wrote a solution using optimal time complexity using LinkedList class. I just could not believe that I wrote the code.

From my own experience to review my past submissions today, I like to get myself more organized, and prepare myself constantly review, learn and work on algorithm every day.

Ideas to work on


One of ideas is to review what I have completed for those 195 algorithms, share those easy level tree algorithms I practiced last few months.

The other idea is to write and share, and then get more active in leetcode discuss community. As long as I am active and learning all the time, I will find ways to improve myself.

The other idea is to start to work on Leetcode weekly contest.

Monday, June 18, 2018

Leetcode last 12 months 42 algorithm submissions

June 18, 2018

Introduction


It feels so good to check in those 42 algorithms I submitted on Leetcode online judge last 12 months. I plan to review what I have worked on and then I find some algorithms to work on again. One of algorithms is Sliding window maximum algorithm. I did not have chance to review the algorithm last 4 weeks, even though I had chance to work on next large element algorithm.

Study once but review once a month. The learning is not one time deal. I need to follow up with more reviews, and also expand my understanding of each algorithm.

Last month I did quickly put together a pdf file to list all algorithm I submitted last 12 months by looking up Leetcode algorithms and then marked algorithms.

Source code on github


Here is the source code folder on my github.


My research topic


I like to choose a small research topic today, now it is 11:34 PM. I like to write down my thoughts right now. I cannot exhaust all hard level algorithm on Leetcode. There is always a new hard level algorithm. Go over those algorithm I work on again, try to explore more on the algorithm.

To train myself, it is better to work on the algorithm with more detail. For example, I can spend over 10 hours to look into Leetcode 239: slide window maximum algorithm, and also blog about my experience and learning.


Friday, August 27, 2021

Leetcode 239: Sliding Window Maximum | My discussion post in 2015 | My warmup practice in Aug. 2021 | Amazon OA

Aug. 27, 2021 

239 LinkedList | C# |  LinkedList API | deque data structure

Here is my discussion post. 

I will warm up and practice using C# in short future. 

Amazon OA in past 12 months

第一题是MaximumNumberinSlidingWindow第二题是Turnstile


Wednesday, November 16, 2016

Learning style - a good tip to share

Nov. 16, 2016

One of daily habit is to look up search keywords through Blogger back office.

Here are the last month search keywords of this blog:
hackerrank bonetrousle
leetcode 146 C#
acm cheat sheet
leetcode 239
topcoder + finding the longest increasing ...
zig-zag traversal of a binary tree in c
camelcase hackerrank solution
pluralsight c++ advanced

Nov. 16, 2016 - one of search from Yahoo.com is about this algorithm:

http://juliachencoding.blogspot.ca/2016/04/hackerrank-connected-cell-in-grid.html


Julia's favorite algorithm - DFS/ BFS algorithm, she did a lot of practice from April - June, 2016. Five months later, it is time to review the algorithm again.

--

So, Julia will refresh the content of those blogs as well, and try to improve the solution/ or blog content as well.

Share the blog statistics of month of November, 2016:




Saturday, August 8, 2015

Leetcode 239: sliding window maximum

August 7, 2015
Julia spent 20-30 minutes to think about solution first, and read the following blogs, write some code as well. She practised three time using C# and here are the details.

C# practices


Here are 3 practice Julia did using LinkedList, List and SortedList. 

1. C# LinkedList

C# code implementation

2. C# List<int>

3. C# SortedList


More detail

Double ended queue is implemented using C# LinkedList class, here is Julia's C# practice code: C# code implementation

Julia chose to study the blog on Leetcode: sliding window maximum

C# code implementation (C# does not have deque class, so using C# List<int>, 
convert Python code implementation to C#, time limit exceeded)

Good workout on C# List<int>, Julia experienced different style on removing head element if out of sliding window. 

Julia chose to read the blog on geekforgeek.com called "maximum of all subarrays of size k". 

Method A: naive solution, time complexity O(nw)
C# practice code is here. 

Method B: using Self-Balancing Tree (Time complexity: O(nk), need to write c# code)

C# practice code is here. 


4. blog:

http://n00tc0d3r.blogspot.ca/2013/04/sliding-window-maximum.html

Good comment about Deque:

We can use a Deque which allow insertions/deletions on both ends. For a Deque implemented by Circular Array/Buffer or Double Linked List, the basic insert/delete operations run in constant time.

discussion of using heap: 
 The first thought might be heap.
By maintaining a heap for all numbers in the window can give us a O(nlogw)-time solution, where
  • building up a heap for initial window takes time O(wlogw)
  • when window moves to the next number, each insertion and deletion take time O(logw) and there are n-w moves in total.
  • after updating the heap, findMax only takes time O(1) since we know the top of heap is the largest.
  •  
So, if w << n, the performance of this solution is good, close to O(n); but if w is not that small, say w = n/3 or n/4, the running time goes up to O(nlogn).

5. blog:   C++ code 
using C++ multiset in the above solution, so try to convert it to C# class using SortedList

C# practice code

6. blog:
http://www.mamicode.com/info-detail-927510.html

Convert Java Script code to C#; I spent over 12 months to try to be expert on Java Script, so much fun to read the Java Script code again, and enjoyed the blog about the analysis. 

Others:
https://github.com/jianminchen/slidingWindowMaximum/blob/master/slidingWindowMaximu5.cs





Thursday, September 13, 2018

Leetcode 239. Sliding window maximum

Sept. 13, 2018

Introduction 


I like to write a solution for the hard level algorithm called sliding window maximum. My last submission on Leetcode is more than 15 month ago.

My practice


It is important for me to review what I have practiced, and learn from my own experience. I shared the code I wrote in August, 2015. Here is the link.

Friday, December 24, 2021

Leetcode discuss: 239. Sliding Window Maximum

Dec. 24, 2021

Here is the link. 

C# | Deque | Optimal time complexity O(N) | LinkedList API | Holiday rush

Dec. 24, 2021
Introduction
It is the day before 2021 Christmas day. I have to rush to warmup algorithms for Microsoft Vancouver code screen this Sunday. I chose to warmup this algorithm, since I came cross the algorithm. Double linkedList is a perfect choice to simulate a deque data structure. In order to get linear complexity to get maximum slide window, do not overdo. Three steps are my choices this time.

Deque | Slide window | C# LinkedList | Tips to share | Lessons learned | Warmup 30 minutes
I chose to write the code using C# and also tried to put together a test case to make sure that it runs perfectly.

I have not written very often C# code in my last two months, since I worked on system design. It is challenge to warm up, I manually walked through the test case, but I still came cross the following errors:

  1. Missing one, if statement: if(i >= k - 1) <- case study: k = 3, i >= 2, not i >=3;
  2. Index out of range, slideWindow[i - k + 1], after my first correction on step 1, I need to change the array's index;
  3. Mix nums[index] with index. nums[LinkedList.First.Value] <- change it using nums[index]

Optimal time complexity O(N) | Maintain the window
It is important to come out linear solution, every index should get into deque exactly once, the deque should maintain index value of array, and those values of index matched should be in nonascending order, kind of monotonic pattern questions for quick prototype.

A simple test case to walk through | Powerful tool to reexamine the algorithm
Run a simple test case:
[1, 3, -1, -3], k = 3
Save index value of the array into slide window, maximum size is 3.
[0]
[1] -> remove 0 <- since nums[1] > nums[0]
[1, 2] -> slideWindow [3]
[1, 2, 3] -> slideWindow[3, 3]

The following C# code runs through Visual studio and the main function passes Leetcode online judge.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _239_sliding_window_maximum
{
    class Program
    {
        static void Main(string[] args)
        {
            var result = MaxSlidingWindow(new int[] { 1, 3, -1, -3, 5, 3, 6, 7 }, 3);
            // [3, 3, 5, 5, 6, 7]
            Debug.Assert(string.Join(",", result).CompareTo("3,3,5,5,6,7") == 0);  
        }

        /// <summary>
        /// Dec. 24, 2021
        /// 239. Sliding Window Maximum
        /// Using C# LinkedList to simulate a deque. The idea is to maintain a nonascending deque so that it is easy to get maximum one 
        /// and also using optimal time complexity O(N) to get maximum window. 
        /// The goal is to keep time complexity linear using deque data structure. 
        /// My warmup practice is to get more experience using C# LinkedList APIs. 
        /// Run a simple test case: 
        /// [1, 3, -1, -3], k = 3
        /// [0]
        /// [1] -> remove 0
        /// [1, 2] -> slideWindow [3]
        /// [1, 2, 3] -> slideWindow[3, 3]
        /// </summary>
        /// <param name="nums"></param>
        /// <param name="k"></param>
        /// <returns></returns>
        public static int[] MaxSlidingWindow(int[] nums, int k)
        {
            if(nums == null || nums.Length < k || k <= 0 )
                return new int[0];

            var linkedList = new LinkedList<int>(); // using index of the array
            var length = nums.Length; 
            var slideWindow = new int[length - k + 1];

            for (int i = 0; i < length; i++)
            {
                var value = nums[i];

                // case 1: remove the first one
                if (linkedList.Count > 0  && (i - linkedList.First.Value ) >= k)
                {
                    linkedList.RemoveFirst();
                }

                // add value to deque if needed
                while (linkedList.Count > 0 && nums[linkedList.Last.Value] < value)
                {
                    linkedList.RemoveLast();
                }

                // always
                linkedList.AddLast(i);

                // add value to slideWindow 
                if (i >= k - 1)
                {
                    slideWindow[i - k + 1] = nums[linkedList.First.Value]; 
                }
            }

            return slideWindow; 
        }
    }
}