Thursday, March 10, 2022

Leetcode discuss: 862. Shortest Subarray with Sum at Least K

 March 10, 2022

Here is the link. 

C# | Design a deque | Review Array - Subarray | 2022 March

March 10, 2022
Introduction
I plan to spend two weeks to prepare for Meta phone screen. I had three onsite interview from Meta in the row from 2019 to 2021, and this time I have to take another phone screen again. I did a few hours research on Leetcode.com, and kept blogging those case study of FB, Google, MSFT interview, and then I found the book through one of sharings. I like to go through those patterns - book chapter: Part VII Problem-patterns, and review all those algorithms. Here is the link of the book. I am reviewing Array - subarray algorithms, here is the list written in the book chapter.

C# | LinkedList | Deque data structure
It is hard for me to review the algorithm using deque. I think that I can do my best, and make sure that deque will work perfectly with test case [3, -2, 5], target = 4.

Time complexity: O(N)

  1. Using O(N) time to calculate prefix sum;
  2. C# LinkedList - a deque
  3. What to remove - PK, remove those ones impossible to be smallest one from the end
  4. What to remove - PK, remove those ones impossible to be smallest one from the beginning.
  5. Study the test case [3, -2, 5]
  6. Read more carefully about discuss post, how deque solve the problem. Here is the link.

Case study: [3, -2, 5], K = 4 | Deque
prefix sum: {3, 1, 6], K = 4, minimum length is 1, start and end index = 2
How to find it?
put index = 0 onto deque
iterate index = 1, deque size is 1, skip;
I think that working on this simple test case is best way to understand the design.

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

namespace _862_minimum_subarray_at_least_k
{
    class Program
    {
        static void Main(string[] args)
        {
            var minimumLength = ShortestSubarray(new int[]{3, -2, 5}, 4);
        }

        /// <summary>
        /// code review: 
        /// 1. Read the book chapter
        /// https://github.com/liyin2015/python-coding-interview
        /// Part VII Problem-patterns
        /// Page 551 algorithm 862
        /// 2. Read the discuss post
        /// https://leetcode.com/problems/shortest-subarray-with-sum-at-least-k/discuss/189039/Detailed-intuition-behind-Deque-solution
        /// 3. Work on test case and test C# code
        /// Time complexity: O(N)
        /// </summary>
        /// <param name="A"></param>
        /// <param name="K"></param>
        /// <returns></returns>
        public static int ShortestSubarray(int[] A, int K)
        {
            if (A == null || A.Length == 0)
                return -1;

            var length = A.Length;
            var prefix = new int[length + 1]; // change from length to length + 1 since failed [2, -1, 2]

            // using O(N) time to build a prefix sum of the array
            prefix[0] = 0;
            for (int i = 0; i < length; i++)
            {
                prefix[i + 1] = prefix[i] + A[i];
            }

            var shortest = length + 1;

            // store index of the array into deque
            var linkedList = new LinkedList<int>();

            // three operations of deque
            // remove_front - it is impossible for the start point
            // append_back - it is possible for new start point
            // remove_back - it is impossible for the start point

            // check current index and first one in dequeue - prefix difference vs K
            // test case: [2, -1, 2]
            for (int i = 0; i < prefix.Length; i++)
            {
                var current = prefix[i];

                // step 1: Remove from deque - end side 
                // argue that: what is inside deque? - possible ranges 
                while (linkedList.Count > 1 && prefix[linkedList.Last.Value] >= current)
                {
                    linkedList.RemoveLast();
                }
                
				// step 2: Add to deque
                linkedList.AddLast(i);

                // step 3: remove from the start of deque
                // 
                while (linkedList.Count > 1 && (current - prefix[linkedList.First.Next.Value] >= K))
                {
                    linkedList.RemoveFirst();
                }

                // step 4: Compare to shortest range 
                if (i > 0 && (current - prefix[linkedList.First.Value] >= K))
                {
                    shortest = Math.Min(shortest, i - linkedList.First.Value);
                }
            }

            return shortest == length + 1 ? -1 : shortest;
        }
    }
}

BC vaccine card

 I plan to visit Bellingham chase bank this Saturday to restore my chase bank account online access. I have to cross the border so that I need to share my BC vaccine card. 


Also I need to show my booster shot vaccine proof as well. 




Book chapter: Part VII Problem-patterns | Li yin, PH.D. Facebook AI | Excellent book chapter with a lot of Leetcode algorithms

March 10, 2022

Here is the link. 

I like to go over the book chapter and review all those algorithms written in the book chapter. I finally figured out what I am looking for after so many hours hard working and blogging. 

I need to review algorithm and data structure in much better organized ways. This book is well-written and a lot of good things about the book can help me to prepare for Meta phone screen. 




Data Structures, Algorithms, Python | Li Yin

 Hands-on Algorithmic

Problem Solving

Data Structures, Algorithms, Python

Modules and Coding Interview Problem

Patterns

Li Yin

February 6, 2022

Here is the link of book. 

In short, this is a middle-to-high level algorithm book designed with cracking coding interviews at hearts. It offers a one-stop coding interview prep experience. The structure of the book:

  • Preparation: introduce the global picture of algorithmic problem solving and coding interviews, learn abstract data structures and highly related and useful math such as recurrence relation, and hands-on Python practice by relating the abstract data structures to Python data structures. Coding is not just code after all.,
  • Principles: we organize the design and principle here so that readers can use them as guidance while not seeking for peculiar algorithm for solving a problem.
  • Classical algorithms: We enhance our algorithm database via learning how to apply the core principles to a variety of classical problems. A database that we can quickly relate to when seeing problems.
  • Coding interview problem patterns: We close our book with the analyzing and categorizing problems by patterns. We address classical and best solutions for each problem pattern.

Besides trying to make the content easy to follow, here summarizes the uniqueness of this book: (1) it offers Python source code that is tailored to be simple so that it would be natural for you to use in interviews (2) all the exercises and examples are from Leetcode problems so that you get to practise online (3) Classical algorithms are explained with design principles. No algorithm is magic. (Check out advanced graph algorithms as an example) (4) problem patterns to help you tackle coding interview questions topic by topic.


How did I come up with this book?

Preparing for the coding interview is not easy! Cracking the coding interview? Nearly impossible for most of us! Luck does play a role in the outcome. So, let's just treat it as a learning process and have some fun!

Computer Science is really not just computer science. It is a combination of all fields; our normal interview problems fall into the enumerative combinatorics and our computer vision mostly consists of Linear Algebra. What really matters is our passion to learn and the ability to apply this knowledge to solve real-life problems.

There are plenty of books out there focusing on either teaching algorithmic knowledge (Introduction to Algorithms, Algorithmic Problem Solving, etc) or introducing the interview process and solving interview problems(Cracking the Coding Interview, Coding Interview Questions, etc), but none of these books truly combine the two. This is a book designed to make up this role in the categorization. Principle, Pattern, and Leetcode Problems make up the core of this book.

This is NOT a book that provides hiring statistics for each company or gives the reader quick tricks in order to pass a few coding interviews. Its purpose is to show you the beauty of algorithmic problem solving in the hope that you will be more passionate and confident about software engineering; the interview questions just set up a playground where we strengthen what we learn.


For Readers

The whole book is compiled as pdf.

For readers, you can read the book as a whole or read chapters selectively following the below links.


Leetcode: Best Posts of 2019

 Top 10 Upvoted 👍

Here is a compilation of the most upvoted posts from users like you! The amount of care and detail put into contructing these posts is no doubt the reason why LeetCoders love them so much.

  1. Google | L5 | MTV | Oct 2019 (1.1k votes)
  2. Amazon | SDE1 | Seattle | Oct 2019 (757 votes)
  3. I Leetcoded (And So Can You!) (734 votes)
  4. From 0 to clearing Uber/Apple/Amazon/LinkedIn/Google (690 votes)
  5. How to effectively use LeetCode to prepare for interviews!! (659 votes)
  6. How I Train Myself For Google Internship Interview (424 votes)
  7. My System Design Template (422 votes)
  8. I've failed 10 interviews and 4 onsites, what should I do? (365 votes)
  9. Google | L4 | Warsaw | Sep 2019 (360 votes)
  10. Google | L3 | Seattle | Sep 2019 (353 votes)

Best Discussion Generated 🗣
We recognize that the road to getting your dream offer can be arduous but we promise you are not the only one feeling that way. Here's some of the posts that has generated some of the most meaningful and encouraging dialogues within LeetCoders.

I've failed 10 interviews and 4 onsites, what should I do?
I Leetcoded (And So Can You!)
Leetcode NOOB (Struggling with easy)
How I improved my problem solving
Anyone having massive anxiety?


Study Materials & Tips 📚
Not sure where to start? Check out these posts:


Technical Phone Interview ☎️
We found this post outstanding because it's not always the clearest as to how technical phone screenings go. Here's a great post and don't forget to hone your Phone interviews with our Mock Interviews
Google initial phone screen with recruiter


Behavioral Interview Experience 🤖
If you've nailed the technical side, don't underestimate the behavioral portion of an interview. Here is a phenomenally compiled list from a LeetCode on their Amazon experience.
Amazon Behavioral questions | Leadership Principles | LP


Detailed Interview Timeline & Questions 🗓
It can be confusing as to how the Interview Timeline can go and the wait can often be the most nerve-racking time. Here's some of the most detailed descriptions of how each of these LeetCoders were given their dream offer with perserverence.

Amazon SDE New grad Timeline
Amazon | SDE2 | Boston | Aug 2019
Amazon | SDE1 | Seattle | Oct 2019
Google | L4 | Warsaw | Sep 2019
Offers from Google/Facebook/Apple/Uber/Snap/etc.. after numerous failures


Real Life Interview Question and Discussion 🦄
Here are some of the most reported and discussed real life questions asked during technical interviews. Join the conversation now to contribute your solution to some of these mind-twisters.
Google | Phone Screen | Stack that supports Min, Max, Avg, and Mode
Google | Phone screen | Remove repeating numbers
Google | String Matching
Amazon Interview Question
Google Phone Interview Question DP


Detailed Problem Analysis 💡
Some concepts are just mind-boggling, so here is some of the best break-down of difficult concepts.
My System Design Template
Design a Logistics System
5 flavors of singleton!

*Above list curated as of December 20, 2019


Update 1(December 26, 2019): Wow! Have you seen this post that got 1.4k upvotes in 4 days and won our Giveaway for 2019? 🤯 Check it out now:
Dynamic Programming Patterns

Update 2,(December 28, 2019): Read this comprehensive interviewing experience from our user as they bare their soul about their journey that had led them to a job offer at Google!
Google | L3 | Bangalore | Dec 2019

Facebook: Get that job at Facebook | Carlos Bueno, an engineer at Facebook, knows how to move Mt. Fuji.

Here is the article.

Last edited March 12, 2021

Get that job at Facebook

Interviewing for a technical job is hard, and so is being the interviewer. You want to get that engineering job at Facebook, and we want to hire the best people (you!). Knowing what to expect on both sides can go a long way toward making the process work better.

 

Preparation is important. Hiring, here and across the industry, is like shooting a few protons into the very large space of your life experience, hoping to get enough information back to say that yes, this specimen is definitely made of elemental awesomium. We're trying to build a picture of your abilities as a professional and a colleague from a handful of data points.

 

How we do it

Every role is different and we are always tweaking things, so don't freak out if your experience is different from what's laid out here. Typically it will start with an email or a phone call from a recruiter. Perhaps they found you online, or you applied directly, or a friend recommended you.  We also have an intern program, where we invite talented students to work with us for a few months.

After talking with a recruiter and passing the basic hurdles, a coordinator will schedule you for a phone screen or an initial in-person interview. If the feedback is good, we'll invite you for a longer series of interviews at our office. If *that* goes well, we will make you an offer. Yay!

 

Technical interviews tend to follow the same general pattern: talk about your past work, some interactive coding, answering anything you're curious about, and selling you on the idea of coming to work for us.

 

Phone screen / Onsite

The initial screening interview is a 45 minute talk with a potential coworker. The idea is to slot you with someone in your general area of expertise. They will explain who they are and what they do, ask you about interesting things from your resume, your skills, motivation, interests, and so on.

 The bulk of the time is spent on coding exercises. The interviewer will send you a link to a collaborative editor and ask you to solve some programming problems. More about that in a sec.

 

Onsite Loop

The loop is several interviews back-to-back on the same day, usually with a lunch break. Instead of coding in a text editor, you will likely be asked to write code on a whiteboard. And of course there will be time to ask the interviewer anything you want.

 

What we look for

These traits are not all we look for, nor all we care about. But here are some of the things that interviewers base their decisions on:

Fit: We're looking for your ability to understand and explain complex ideas. We look for a healthy level of enthusiasm, curiosity and motivation. Interviewers are evaluating you as a potential colleague. We have a ridiculous ratio of users to engineers and ship code five days a week. We want people who know how to make a large impact, who can move quickly, make bold choices, and be transparent about what they are doing.

 

Generalism: We need many kinds of specialists, but we also look for people who can fill other roles in a pinch. This means understanding the "stack" above and below your area of expertise. Bonus points for having multiple areas of expertise. It's not unusual for someone at Facebook to work on machine learning, then move on to web performance, build and maintain a new backend tool, then spend a year on photos.

 

Architecture: Can you arrive at an answer in the face of unusual constraints? We want to see how well you can visualize the entire problem and solution space. We also want to see how much you've thought about Facebook in particular and some of the unique problems we face. How would you architect a world-wide video distribution system? Or Facebook chat?

Coding: We don't ask puzzle-type questions, where you need to know a trick. Even so, the coding questions you get asked may sound contrived. This is because they are contrived, in the sense of being designed for a special purpose. They have to be simple enough to explain in a few minutes and solvable in 10 to 30 minutes. But they must also require knowledge, skill, and concentration to solve.

 

Good coding problems are fractal in nature. They can be extended arbitrarily to gauge the depth of your knowledge. For example, you might be asked to solve a problem any way you want. Then you'll be asked to solve it again in constant space or sub-linear time.

 

Incidentally, the ability to give total focus to a problem, no matter how basic it sounds at first, is something we pay close attention to. How you attack a problem is at least as important as the answer.

We will ask you to do a *lot* of coding during the interview process, because programming ability tends to correlate strongly with how well people perform as employees. We even have a large set of take-home questions. It can't hurt to check them out and maybe solve a couple before you even submit your resume.

 

How to Prepare

Steve Yegge of Google wrote an excellent post about interview prep a few years ago. If you haven't read it, go read it. If you have, go read it again. The tips Yegge lists are very good, though I have never seen anyone bring their own whiteboard markers. I'll paraphrase some of it here and add some more:

 

Take your time preparing. Do code katas and practice interviewing with friends. Try solving the interview questions on our site. See our tech talks to get a feel for how we do things and the scale of problems we're trying to solve.

For phone screens, make sure you are in a quiet place with a good internet connection. Headphones are handy. I forgot this during my first interview with Facebook, and had to type code while keeping the phone jammed between shoulder and ear, like a nerdy T-Rex.

 

Practice writing code in a simple text editor without syntax highlighting or completion macros. Don't let little surprises throw you off your stride during the interview.

 

Impress us with your mastery of whatever language you're best at. Don't use a language you know less well because it's trendy or you think it will please the interviewer. This is a very common pitfall.

 

More generally, skills on your resume are fair game. If it says "expert in X," we will try to schedule you with a proven expert in X, so be prepared. If you are not, leave it off. I'd rather have a short list of the things you're awesome at than pages of everything you've ever done.

 A good skill to cultivate is the ability to change your point of view at will. Sometimes you'll encounter a problem that seems like it should have an elegant solution, but in fact must be brute-forced or approximated. If you're stuck on a problem, try to think of any way to solve it, no matter how clumsy or inefficient. Then improve on it. Getting something that works is better than nothing.

 

Hard training makes for an easy battle. Brush up on techniques that you may not use every day, but are very useful when you need them: recursion, graph theory, tree traversal, combinatorial problems, etc.

 

You might be asked to implement some well-known library functions. Knowing at least a little bit about how things work under the hood is highly recommended.

 

Another kind of coding question might be parsing some data format or mini-language. Aside from CS nerd-points, these problems exercise your ability to reason about edge cases and handle lots of state in your head.

 Give feedback. We regularly survey candidates about the interview process and take feedback seriously.

 

Ask questions! Take advantage of the time to ask your interviewer about working life, bootcamp, the interview process itself, how the company is organized, or really anything at all. I recently spent a few minutes at the end of an interview chatting about power efficiency in our datacenters. The candidate was genuinely curious and I did my best to answer. Always remember that you are interviewing us as much as the other way around.

 

Above all, relax! And if you are on the fence about applying to Facebook, do it. I've worked at companies of all kinds, from two-person startups to billion-dollar government projects. Facebook has the resources and leverage of a large company, but as an engineer you have freedom and responsibility far beyond the typical. That's how we punch above our weight. It's an amazing combination that you don't find very often. Check out facebook.com/careers.

 

Carlos Bueno, an engineer at Facebook, knows how to move Mt. Fuji.