Latest Entries »

Minimum Size Subarray Sum

https://leetcode.com/problems/minimum-size-subarray-sum/

My solution:

func minSubArrayLen(target int, nums []int) int {
n := len(nums)
if n == 0 {
return 0
}
ans := n + 1
sums := make([]int, n+1)
for i:=1; i<n+1; i++ {
sums[i] = sums[i-1] + nums[i-1]
}

for i:=1; i<n+1; i++ {
toFind := sums[i-1] + target
bound := lowerBound(sums, toFind, i)
if bound != -1 {
ans = min(ans, bound - i + 1)
}
}
if ans == n+1 {
return 0
}
return ans
}

func lowerBound(nums []int, target int, lowStart int) int {
low, high := lowStart, len(nums)-1
for low <= high {
mid := low + (high-low)>>1
if nums[mid] < target {
low = mid + 1
} else {
if mid == 0 || nums[mid-1] < target {
return mid
} else {
high = mid - 1
}
}
}
return -1
}

This question is similar to https://leetcode.com/problems/shortest-subarray-with-sum-at-least-k/submissions/ except we can only have positive integers in this question while the other can have negative number. The solution assumes the prefix sum array (sums) is strictly increasing. This is a key assumption for the binary search approach used in the lowerBound function to work correctly. But the assumption breaks in the other problem.

The test case [44,-25,75,-50,-38,-42,-32,-6,-40,-47] with target 19 is a good example where my solution fails. My method might skip some valid subarrays that meet the condition.

Here’s an approach using a deque (double-ended queue) to efficiently find the shortest subarray for https://leetcode.com/problems/shortest-subarray-with-sum-at-least-k/submissions/:

  1. Use a deque to store indices of the sums array. The deque will help in efficiently finding the minimum length subarray.
  2. Iterate through the array while maintaining the prefix sums.
  3. For each new prefix sum, pop elements from the back of the deque if they are greater than or equal to the current prefix sum. This is because such elements will not contribute to a shorter subarray.
  4. Check if the front of the deque can form a valid subarray that meets or exceeds the target sum. If so, update the answer accordingly and pop it from the front.
  5. Add the current index to the deque.

This approach ensures that the deque always has indices in increasing order of their corresponding prefix sums, and it effectively finds the shortest subarray that meets the condition.

Why do we need an increasing order of their prefix sums? When the prefix sum at the current index (let’s call it sum[i]) is less than or equal to the prefix sum at the back of the deque (say sum[dequeBack]), it indicates that the subarray from dequeBack to i has a non-positive sum (could be zero or negative). Adding the segment from dequeBack to i doesn’t increase the sum. In fact, it could potentially decrease the sum or keep it the same.

func shortestSubarray(nums []int, k int) int {
n := len(nums)
deque := []int{}

sums := make([]int, n+1)
for i:=0; i<n; i++ {
sums[i+1] = sums[i] + nums[i]
}

ans := n+1

for i:=0; i<n+1; i++ {
for len(deque) > 0 && sums[i] - sums[deque[0]] >= k {
            // subarray [deque[0]+1, I]
ans = min(ans, i-deque[0])
deque = deque[1:]
}

for len(deque) > 0 && sums[i] <= sums[deque[len(deque)-1]] {
deque = deque[:len(deque)-1]
}

deque = append(deque, i)
}

if ans == n+1 {
return -1
}

return ans
}

  1. questions to ask: https://techbeacon.com/5-killer-questions-software-engineers-should-ask-their-next-job-interview

https://en.wikipedia.org/wiki/End-to-end_delay

OWD = propagation delay + queuing delay + tx (transmission) delay + processing delay

prp delay = dist / c, where c is the speed of light (this is also the ping command time)
queueing delay = f(cross traffic)
tx delay = 64 bytes / nic cap
nic cap = 10 Gbps
for 64 bytes data transfer, tx delay = 64*8/10Gbps
for 23 Mb data transfer, tx delay = 23MB/10Gbps = 23*8/10 ms

We can see tx delay is usually small.

Notes: The story of Art

As a matter of fact it was usually those artists who reads the scripture with greatest devotion and attention who tried to build up in their minds an entirely fresh picture of the instance of The sacred story. They try to forget all the paintings they had seen and to imagine what it must have been like when the Christ child playing the manger and the Shepherds came to adore him, or when the fishermen began to preach the gospel. It has happened time and again that is such efforts of a great artist to read the old a text with entirely fresh eyes have shocked and outraged thoughtless people.

A typical scandal of this kind flared up round Caravaggio, a very Bold and The Revolutionary Italian painter who worked around about 1600. He was given the task of painting a picture of St Matthew for the altar of church in Rome. The Saint was to be represented writing the gospel, and to show the gospel were the word of God, and Angel was to be represented inspiring his writings. Caravaggio who was a highly imaginative and uncompromising Young artist thought hard about what it must have been like when an elderly poor Working Man, a simple population suddenly had to sit down to write a book. And so he painted a picture of St Matthew, figure 15 with a bald head and a bare Dusty feet awkwardly gripping the huge volume, anxiously wrinkling his brow under the unaccustomed strain of writing.

Caravaggio, Saint Matthew, 1602

Caravaggio, Saint Matthew, 1602

By his side he painted a youthful Angel who sings just that you have arrived from on high and who gently guides the labor’s hand as a teacher may do to a child. When Caravaggio deliver this picture to the church where it was to be placed on the altar people were scandalized at what they took to be a lack of respect for the saint. The painting was not accepted and a Caravaggio headed to try again. This time he took no chances. He kept it strictly to the conventional ideas of what an angel and a saint should look like, Figure 16. The outcome is still quite a good picture, for Caravaggio try hard to make it look Lively and interesting, but we feel that it is less honest and sincere than the first had been.

Caravaggio Saint Matthew, 1602

Caravaggio Saint Matthew, 1602

Figure 26 is a model of a chieftain’s house of the Haida tribe of the Northwest with three so-called totem poles in front of it. we may see only a jumble of ugly masks, but to the Native this pole illustrates an old Legend of his tribe. The legend itself May strike us as nearly as old and incoherent as its representation but we ought no longer to feel surprised that native ideas differ from ours.

20161225_182014

Model of a nineteenth-century Haida chieftain’s house, north-west coast Indians

Once there was a young man in the town of Gwais Kun who used to laze about on his bed the whole day till his mother-in-law remarked on it; he felt ashamed, went away and decided to slay a monster which lived in the lake and fed on humans and whales. With the help of a fairy bird he made a trap of tree trunk and then dangled two children over it as the bait. The monster was caught, the young men dressed in his skin and caught fishes, which he regularly left it on his critical mother-in-law’s doorstep. She was so flattered at these expected offerings that she thought of herself as a powerful witch. When the young man undeceived her at last she felt so ashamed that she died.

All the participants in the story of represented on the Central Pool. The Mask below the entrance is one of the whales the monster used to eat. The big mask above the entrance is the monster; on top of it that human form of the unfortunate mother-in-law. The mask with a beak over her is a bird who helped the hero and he himself is seen further up dressed in The Monster’s skin with fish he has caught. The human figures at the end are the children the hero used as bait.

Figure 30 represents the statue from Mexico which is believed that today from the Aztec period, the last before the conquest. Scholars think that it represents the rain God whose name was tlaloc. in the tropical zone, rain is often a question of life or death for the people; for without the rain their crops May Fail and they may have to starve. No wonder that the god of the Rains and The thunderstorms assumed in their minds the shape of a terrifying powerful demon. the lightning in the sky appealed to the imagination like a big Serpent and many American people therefore considered the rattlesnake to be sacred and mighty being. if we look more closely at it and figure it all out we see in fact that his mouth is formed of two heads of rattlesnakes facing each other with their big poisonous fangs protruding from the jaws and that his nose to seem to be formed out of the Twisted bodies of the snakes. Perhaps even his eyes might be seen as coiled serpents. we see how far the ideas of building up a face out of giving forms carried away from our ideas of Life likes capture.

 

76ae0125e0a4b37c9c4625b2aefecf3e

Tlaloc, the Aztec rain god, 14th-15th century

 

Diary March 2016

3.1
LingXiao wants Meili to make dumpling dough and wrappers.

3.2
Please move yourself into groups of four. Break into teams, face your teammates. I will ask each group to present their discussions. Choose your spokesman.

3.3
Meili bleed a lot during periods. How can she replenish the blood?

3.4
Using boa to build a suite of semantic queries and gather experimental data from github repositories is a terrific idea.

3.5
Meili wants to cook braised chicken with chesnut.

3.6
The plan of Tower Run at Du Bois Library was to go up, up, up, in the stairwell, on foot — all the way to the top, from the Lower Level to Floor 26.

3.7
Donald Trump is the Leicester city of American politics.

3.8
My mom used to be a tailor.

3.9
I unclogged my slow-draining bath tub drain.

3.10
Meili doesn’t like to take medicine.

3.11
Don’t check and reply to an email all the time.

3.12
When I crossed street today, I saw Pastor Greg and his son walking their dog.

3.13
We don’t have money to hire a wedding band. Instead, we asked David and Renee in our church to sing and play music for us.

3.14
Tianqi bought a used suv from a car rental company at a low price.

3.15
We don’t need to sublet our room because we are finishing our lease.

3.16
A rookie driver finds it hard to change lanes.

3.17
People said I became more handsome. I think one of the reasons may be food. I drank a lot milk and yogurt every day here. I didn’t do that much in China.

3.18
Meili is my hairdresser. I don’t go to barber’s shop for years.

3.19
To be a dad, first learn how to change a diaper.

3.20
I can order scampi using Amazon prime now. Those can be delivered within one hour.

3.21
Before a semester, we have to sign TA or RA contracts.

3.22
Could you snap a picture for us?

3.23
Meili and I scuba dived at hanauma bay.

3.24
It’s still not easy to be an anchorman even though they can read a teleprompter.

3.25
When I become a dad, I want to take my kids to a movie and Disney world.

3.26
It’s hard to find a cobbler in Amherst.

3.27
Meili booked a honeymoon suite for us.

3.28
I often lock myself out of the car.

3.29
Do you know where to buy a crib for babies?

3.30
When two muslin prayer hopped on a subway, other riders found their activity suspicious and dialed 911.

3.31
I am already taken. I married my wife on Sep. 20 2014.

Diary February 2016

2.1
why do we sing take me out to the ball game when we’re already at the ball game?

2.2
Hurt my knee running today so I decided to just start walking through the pain till I can run again.

2.3
I was riding a bicycle to the UMass baseball game.

2.4
Life is like riding a bicycle. To keep your balance, you must keep moving.

2.5
Being a PhD reduces the risk of Alzheimer’s by over 50% because I am thinking a lot.

2.6
When I was skidding bicycle, I felt nothing but the wind and myself.

2.7
Meili said her eyes often felt tired and sore.

2.8
Emma and Bobby are talking about how they feel afte the new episode of Game of Thrones.

2.9
Wow! Just wow! Very strong endorsement of *current* static analysis tools despite their false positive rate. Looks like the industry is changing its attitude very rapidly on this matter. Microsoft tools help a lot. Coverity, also.

2.10
He wishes whole seasons of GoT came out so he could watch it all at once and get it done with. So exhausting dodging spoilers every week.

2.11
It’s thrilling to watch Game of Throne.

2.12
Emery said half of ICSE papers are garbage.

2.13
I don’t like this programming committee, full of SE yahoos.

2.14
There is a long stretch of car inspection line. At least 2 hours.

2.15
A tragic shooting happened at the UCLA.

2.16
It’s not safe to keep leftover dish too long.

2.17
Maybe we need a budge for monthly expenses so that we are able to pay the house price.

2.18
Thanks for your clarification.

2.19
I received a package that is 4 times as large as a shoe box.

2.20
Short grain sweet rice porridge is not hard to cook.

2.21
BIcycling is better exercise than walking: i sweat up the road to the school by riding a bicycle, but never do so when walking.

2.22
My heart cries a little every time I walk past my bicycle and don’t ride it.

2.23
To transfer to Meili’s insurance, I have to ask my insurance provider to provide a certificate coverage letter proving my insurance will be terminated. Otherwise, I will have to find an insurance at the Mass health connector.

2.24
Green card application cutoff date progress or retrogress back and forth.

2.25
Spicy fish goes great with an ice cold beer or sorbet.

2.26
Brazil was defeated by Peru, thus eliminated from Copa America.

2.27
We will decide to watch the Copa America final depending on which teams are playing in the final.

2.28
i want to buy the mount for phone in car so that i can read it while i am driving.

2.29
There are a lot of things u can’t control, like skiing. We should let go let God control at that moment.

Diary January 2016

1.1
I checked your submission history. I guess you have made 3 tries. We only allow 3 attempts to answer the question correctly. I have the value of “Penalty for each incorrect try” set to 33.3%. That means that if you were to get the question correct on the 1st attempt, it would give you 100% of the point value of the question, on the second attempt, 66% of the point value of the question, on the third attempt 33% of the point value, and it would not allow you to have a 4th attempt because there would be no points left.

1.2
You didn’t micromanage him.

You would meet regularly one-on-one meeting.

1.3
We have discussion next Friday. M

Sometimes all it takes is another pair of eyes 🙂

akeup exam will be scheduled at different time.

1.4
The exam only goes until the end of what is week 4 on the schedule.

1.5
i dont have a document scanner so hopefully this picture can suffice.

1.6
In your search method, the way of detecting end of the list does
not look right: (*p)->next != NULL

1.7
HMTL and Latex don’t care about line breaks.

1.8
Could you adjust the blinds to keep out the glare?

1.9
– I have 168 students.
– One hour for each student. I happen to know there are 168 hours per week.

1.10
John’s words:
1) I’ll come back to that.
2) Did you have questions?

1.11
Import in Java is only there as it allows the use of shorthand. You don’t necessarily need import. It is totally different with include.

1.12
– Does the order of define matter?
– No.

1.13
Afer ultrasound in uhs:
– Do you have the parking ticket?
– No.
– I’ll let u out.

1.14
Two people who happened to stay in the same high school published a paper 30 years ago published a paper today. Isn’t this wacky?

1.15
If his thing falls through, we don’t need to contact another person.

1.16
During my interview with Jane street, I cannot even answer one single thing, even my name.

1.17
It will be primarily on material not covered the the mid-term, but, this being a technical course, will, of necessity, be somewhat cumulative.

1.18

Addiction is not a choice. It’s a disease.

1.19

I have been thinking for a long time before finding the courage to send the message to WangBuqin.

1.20

The doctor told me I may have loose bowels after the CT scan.

1.21

As always, I’m humbled by my three seconds of association with so many brilliant people who’ve worked their tails off to better their lives and our world.

1.22

A tall cold coke after a basketball game is the most rewarding ever.

1.23
Do you hv the info that was given out last year on free airport pick up?

1.24
I am in for either Thursday or Friday.

1.25
Today when I was running in the gym and tries to listen to music on spotify, no song seems to be the right song. Only All About That Bass from Meghan Trainor seems ok.

1.26
Hmm coincident that stressed spelled backwards is desserts.

1.27
Karen invites to a “bon-voyage” gathering to say goodbye to some of us leaving. Coincident that we don’t have tuanqi.

1.28
Since she has mono, she always sleep more than other people.

1.29
To be my friend all you have to do is make me laugh, sing in the car with me, love adventures, & respond to my texts & wechats.

1.30
Meili and I would love to join. Thank you for inviting us! We will be a little late because Meili gets off from work around 5:30 and it takes 1 hour to drive to your house. Don’t wait for us:)

1.31
Yeah, there’s a chance of rain in the afternoon. So what? Humans are fully immersible. Dress accordingly.

C is the man

“The C Paradox” (by Anonymous, on 4chan 2011-08-06)

I don’t think C gets enough credit. Sure, C doesn’t love you. C isn’t about love–C is about thrills. C hangs around in the bad part of town. C knows all the gang signs. C has a motorcycle, and wears the leathers everywhere, and never wears a helmet, because that would mess up C’s punked-out hair. C likes to give cops the finger and grin and speed away. Mention that you’d like something, and C will pretend to ignore you; the next day, C will bring you one, no questions asked, and toss it to you with a you-know-you-want-me smirk that makes your heart race. Where did C get it? “It fell off a truck,” C says, putting away the boltcutters. You start to feel like C doesn’t know the meaning of “private” or “protected”: what C wants, C takes. This excites you. C knows how to get you anything but safety. C will give you anything but commitment. In the end, you’ll leave C, not because you want something better, but because you can’t handle the intensity. C says “I’m gonna live fast, die young, and leave a good-looking corpse,” but you know that C can never die, not so long as C is still the fastest thing on the road.

This content is password-protected. To view it, please enter the password below.

Diary December 2015

12.1
In my experience, I haven’t had issues with font sizes when the VM wasn’t expecting a high resolution screen. So I cannot give u any advice.

12.2
Did u list this course as a core course?

12.3
There are two exams we have to proctor. Which one of you take which one of them?

12.4
I have opened up the quiz for you. It is open now and due in one week (Feb. 4, 11:59 pm).

12.5
The assignment is due in less than 40 mins. Make sure you submit your code before that.

12.6
The Spring 2016 semester is now in full swing.

12.7
We don’t just admire God. We worship him.

12.8
Maybe we can remove the chair or turn up the heat to get rid of people.

12.9
Nick, if the timestamp is before the due date (2/1 11:59 pm), please give Trevor credit.

12.10
Yannis said why you cannot use z3 fixedpoints. That’s kind of aha moment.

12.11
We are used to buying a bag of flour and make soft doughs.

12.12
There is more to life than work.

12.13
After a long flight, this is a pain that’s gonna linger. I’m still nauseous.

12.14
Congratulations to Leonardo. Eating that raw bison is so much worth it.

12.15
Get out of here: An exclamation of disbelief

12.16
I’ll pass that. 我还是算了吧。

12.17
U r a step ahead of me.

12.18
I don’t know how to programming in virtual memory without going into the kernel mode. Maybe we an just give some textbookish questions.

12.19
Would you mind watching my stuff while I am going into the bathroom?

12.20
Let’s get together for a festive luncheon.

12.21
Someone help me because I can’t handle his cuteness

12.22
HuangZhu CANNOT HANDLE DIFFERING options!

12.23
Hi, optical service. This is Barb. May I help you?

12.24
Also, note that lines is an array of memory that should be iterated over calling make_block at each iteration.

12.25
Sometimes all it takes is another pair of eyes 🙂

12.26
Another pair of eyes would be extremely helpful.

12.27
ooof I would really like to go to England one of these days

12.28
When will the slides be up from today’s lecture?

12.29
You get one week off.

12.30
You are supposed to code it up.

12.31
I know that’s pushing. But it’s good practice.

Create your own website, free on WordPress.com.Create your own website.
Start free