LeetCode - Algorithms - 1275. Find Winner on a Tic Tac Toe Game

Problem

1275. Find Winner on a Tic Tac Toe Game

Tic-tac-toe

Java

my solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
class Solution {
public String tictactoe(int[][] moves) {
final int len = moves.length;
List<int[]> listX = new ArrayList<int[]>();
List<int[]> listO = new ArrayList<int[]>();
for (int i = 0; i < len; i++) {
if (i % 2 == 0)
listX.add(moves[i]);
else
listO.add(moves[i]);
}
String r = "";
if (hasWin(listX))
r = "A";
else if (hasWin(listO))
r = "B";
else if (len == 9)
r = "Draw";
else
r = "Pending";
return r;
}

private boolean realContain(List<int[]> list, int[][] arr) {
boolean b = true;
for (int i = 0; i < arr.length; i++) {
boolean b2 = false;
for (int j = 0; j < list.size(); j++) {
b2 = b2 || ((arr[i][0] == list.get(j)[0]) && (arr[i][1] == list.get(j)[1]));
}
b = b && b2;
}
return b;
}

private boolean hasWin(List<int[]> list) {
int[][] a1 = {{0, 0},{0, 1},{0, 2}};
int[][] a2 = {{1, 0},{1, 1},{1, 2}};
int[][] a3 = {{2, 0},{2, 1},{2, 2}};
int[][] a4 = {{0, 0},{1, 0},{2, 0}};
int[][] a5 = {{0, 1},{1, 1},{2, 1}};
int[][] a6 = {{0, 2},{1, 2},{2, 2}};
int[][] a7 = {{0, 0},{1, 1},{2, 2}};
int[][] a8 = {{0, 2},{1, 1},{2, 0}};
boolean r = realContain(list, a1) || realContain(list, a2) || realContain(list, a3)
|| realContain(list, a4) || realContain(list, a5) || realContain(list, a6)
|| realContain(list, a7) || realContain(list, a8);
return r;
}
}

Submission Detail

  • 100 / 100 test cases passed.
  • Runtime: 2 ms, faster than 8.21% of Java online submissions for Find Winner on a Tic Tac Toe Game.
  • Memory Usage: 38.9 MB, less than 6.40% of Java online submissions for Find Winner on a Tic Tac Toe Game.

The Death of the Moth

by Virginia Woolf

Moths that fly by day are not properly to be called moths; they do not excite that pleasant sense of dark autumn nights and ivy-blossom which the commonest yellow-underwing asleep in the shadow of the curtain never fails to rouse in us. They are hybrid creatures, neither gay like butterflies nor sombre like their own species. Nevertheless the present specimen, with his narrow hay-coloured wings, fringed with a tassel of the same colour, seemed to be content with life. It was a pleasant morning, mid-September, mild, benignant, yet with a keener breath than that of the summer months. The plough was already scoring the field opposite the window, and where the share had been, the earth was pressed flat and gleamed with moisture. Such vigour came rolling in from the fields and the down beyond that it was difficult to keep the eyes strictly turned upon the book. The rooks too were keeping one of their annual festivities; soaring round the tree tops until it looked as if a vast net with thousands of black knots in it had been cast up into the air; which, after a few moments sank slowly down upon the trees until every twig seemed to have a knot at the end of it. Then, suddenly, the net would be thrown into the air again in a wider circle this time, with the utmost clamour and vociferation, as though to be thrown into the air and settle slowly down upon the tree tops were a tremendously exciting experience.

The same energy which inspired the rooks, the ploughmen, the horses, and even, it seemed, the lean bare-backed downs, sent the moth fluttering from side to side of his square of the window-pane. One could not help watching him. One was, indeed, conscious of a queer feeling of pity for him. The possibilities of pleasure seemed that morning so enormous and so various that to have only a moth’s part in life, and a day moth’s at that, appeared a hard fate, and his zest in enjoying his meagre opportunities to the full, pathetic. He flew vigorously to one corner of his compartment, and, after waiting there a second, flew across to the other. What remained for him but to fly to a third corner and then to a fourth? That was all he could do, in spite of the size of the downs, the width of the sky, the far-off smoke of houses, and the romantic voice, now and then, of a steamer out at sea. What he could do he did. Watching him, it seemed as if a fibre, very thin but pure, of the enormous energy of the world had been thrust into his frail and diminutive body. As often as he crossed the pane, I could fancy that a thread of vital light became visible. He was little or nothing but life.

Yet, because he was so small, and so simple a form of the energy that was rolling in at the open window and driving its way through so many narrow and intricate corridors in my own brain and in those of other human beings, there was something marvellous as well as pathetic about him. It was as if someone had taken a tiny bead of pure life and decking it as lightly as possible with down and feathers, had set it dancing and zig-zagging to show us the true nature of life. Thus displayed one could not get over the strangeness of it. One is apt to forget all about life, seeing it humped and bossed and garnished and cumbered so that it has to move with the greatest circumspection and dignity. Again, the thought of all that life might have been had he been born in any other shape caused one to view his simple activities with a kind of pity.

After a time, tired by his dancing apparently, he settled on the window ledge in the sun, and, the queer spectacle being at an end, I forgot about him. Then, looking up, my eye was caught by him. He was trying to resume his dancing, but seemed either so stiff or so awkward that he could only flutter to the bottom of the window-pane; and when he tried to fly across it he failed. Being intent on other matters I watched these futile attempts for a time without thinking, unconsciously waiting for him to resume his flight, as one waits for a machine, that has stopped momentarily, to start again without considering the reason of its failure. After perhaps a seventh attempt he slipped from the wooden ledge and fell, fluttering his wings, on to his back on the window sill. The helplessness of his attitude roused me. It flashed upon me that he was in difficulties; he could no longer raise himself; his legs struggled vainly. But, as I stretched out a pencil, meaning to help him to right himself, it came over me that the failure and awkwardness were the approach of death. I laid the pencil down again.

The legs agitated themselves once more. I looked as if for the enemy against which he struggled. I looked out of doors. What had happened there? Presumably it was midday, and work in the fields had stopped. Stillness and quiet had replaced the previous animation. The birds had taken themselves off to feed in the brooks. The horses stood still. Yet the power was there all the same, massed outside indifferent, impersonal, not attending to anything in particular. Somehow it was opposed to the little hay-coloured moth. It was useless to try to do anything. One could only watch the extraordinary efforts made by those tiny legs against an oncoming doom which could, had it chosen, have submerged an entire city, not merely a city, but masses of human beings; nothing, I knew, had any chance against death. Nevertheless after a pause of exhaustion the legs fluttered again. It was superb this last protest, and so frantic that he succeeded at last in righting himself. One’s sympathies, of course, were all on the side of life. Also, when there was nobody to care or to know, this gigantic effort on the part of an insignificant little moth, against a power of such magnitude, to retain what no one else valued or desired to keep, moved one strangely. Again, somehow, one saw life, a pure bead. I lifted the pencil again, useless though I knew it to be. But even as I did so, the unmistakable tokens of death showed themselves. The body relaxed, and instantly grew stiff. The struggle was over. The insignificant little creature now knew death. As I looked at the dead moth, this minute wayside triumph of so great a force over so mean an antagonist filled me with wonder. Just as life had been strange a few minutes before, so death was now as strange. The moth having righted himself now lay most decently and uncomplainingly composed. O yes, he seemed to say, death is stronger than I am.


  • The Death of the Moth, and Other Essays
  • Woolf battled mental illnesses throughout her life, and eventually committed suicide by drowning herself in 1941, a year before this essay was published.
  • Virginia Woolf, after a vain effort imagining how Shakespeare “coined his words,” writes in her diary: Indeed, I could say that Shakespeare surpasses literature altogether, if I knew what it meant. (Shakespeare, Newton, and Beethoven: Or, Patterns of Creativity, by Subrahmanyan Chandrasekhar)

Rules Kids Won’t Learn in School

  1. Life is not fair. Get used to it.

  2. The real world won’t care as much about your self-esteem as much as your school does. It’ll expect you to accomplish something before you feel good about yourself.

  3. Sorry, you won’t make $40,000 a year right out of high school. And you won’t be a vice president or have a car phone either. You may even have to wear a uniform that doesn’t have a Gap label.

  4. If you think your teacher is tough, wait till you get a boss. He doesn’t have tenure, so he tends to be a bit edgier. When you screw up, he’s not going to ask you how you feel about it.

  5. Flipping burgers is not beneath your dignity. Your grandparents had a different word for burger flipping. They called it opportunity. They weren’t embarrassed making minimum wage either. They would have been embarrassed to sit around talking about Kurt Cobain all weekend.

  6. It’s not your parents’ fault. If you screw up, you are responsible. This is the flip side of “It’s my life,” and “You’re not the boss of me,” and other eloquent proclamations of your generation. When you turn 18, it’s on your dime. Don’t whine about it, or you’ll sound like a baby boomer.

  7. Before you were born your parents weren’t as boring as they are now. They got that way paying your bills, cleaning up your room and listening to you tell them how idealistic you are. And by the way, before you save the rain forest from the blood-sucking parasites of your parents’ generation, try delousing the closet in your bedroom.

  8. Your school may have done away with winners and losers. Life has not. In some schools, they’ll give you as many times as you want to get the right answer. Failing grades have been abolished and class valedictorians scrapped, lest anyone’s feelings be hurt. Effort is as important as results. This, of course, bears not the slightest resemblance to anything in real life.

  9. Life is not divided into semesters, and you don’t get summers off. Not even Easter break. They expect you to show up every day. For eight hours. And you don’t get a new life every 10 weeks. It just goes on and on. While we’re at it, very few jobs are interested in fostering your self-expression or helping you find yourself. Fewer still lead to self-realization.

  10. Television is not real life. Your life is not a sitcom. Your problems will not all be solved in 30 minutes, minus time for commercials. In real life, people actually have to leave the coffee shop to go to jobs. Your friends will not be as perky or pliable as Jennifer Aniston.

  11. Be nice to nerds. You may end up working for them. We all could.

  12. Smoking does not make you look cool. It makes you look moronic. Next time you’re out cruising, watch an 11-year-old with a butt in his mouth. That’s what you look like to anyone over 20. Ditto for “expressing yourself” with purple hair and/or pierced body parts.

  13. You are not immortal. (See Rule No. 12.) If you are under the impression that living fast, dying young and leaving a beautiful corpse is romantic, you obviously haven’t seen one of your peers at room temperature lately.

  14. Enjoy this while you can. Sure parents are a pain, school’s a bother, and life is depressing. But someday you’ll realize how wonderful it was to be a kid. Maybe you should start now. You’re welcome.


This list was the work of Charlie Sykes, author of the 1996 book Dumbing Down Our Kids: Why American Children Feel Good About Themselves But Can’t Read, Write, Or Add. Sykes’ rule list form the meat of Sykes’ 2007 book, 50 Rules Kids Won’t Learn in School: Real-World Antidotes to Feel-Good Education.


LeetCode - Algorithms - 1492. The kth Factor of n

Problem

1492. The kth Factor of n

Java

simple

© https://leetcode.com/problems/the-kth-factor-of-n/discuss/993800/Java-100-Fast-or-Easy-Solution

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public int kthFactor(int n, int k) {
int count = 0;
for (int i = 1; i <= n; i++) {
if (n % i == 0)
count++;
if (count == k)
return i;
}
return -1;
}
}

Submission Detail

  • 207 / 207 test cases passed.
  • Runtime: 1 ms, faster than 43.12% of Java online submissions for The kth Factor of n.
  • Memory Usage: 35.5 MB, less than 90.14% of Java online submissions for The kth Factor of n.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import java.util.ArrayList;
import java.util.List;

class Solution {
public int kthFactor(int n, int k) {
List<Integer> list = new ArrayList<Integer>();
for (int i = 1; i <= n; i++) {
if (n % i == 0)
list.add(i);
}
if (list.size() < k)
return -1;
else
return list.get(k-1);
}
}

Submission Detail

  • 207 / 207 test cases passed.
  • Runtime: 1 ms, faster than 43.15% of Java online submissions for The kth Factor of n.
  • Memory Usage: 35.8 MB, less than 48.68% of Java online submissions for The kth Factor of n.

Canadian English Slangs & Phrases

Canadian English is in some ways midway between British and American varieties. The written standard is very close to that of British English, but American spellings are quite common. Informal speech has a distinctly American flavour and pronunciation is fairly close to that of the northern United states. Canadian vocabulary naturally includes words reflecting the local environment and culture, many of them taken from the native American languages spoken in Canada: for instance husky, moose, toboggan, anorak, kayak. French, the mother tongue of around one third of Canadians, has also given words to Canadian English vocabulary, e.g. cache(a hiding place). — Michael Swan, Practical English Usage, Fourth Edition

© Moving To Canada? Here Are 75 Canadian English Slangs & Phrases You Must Know

Are You Hungry?

Double Double

an oversized cup of coffee with 2 creams and 2 sugars

homo milk

homogenised/whole milk

Tim Hortons’ Timbits

bite-sized fried-dough confectionery similar to American doughnuts but uniquely Canadian (they’ve been around since the 70s!)

serviettes

paper napkins

A napkin, serviette or face towelette is a rectangle of cloth used at the table for wiping the mouth and fingers while eating. It is usually small and folded, sometimes in intricate designs and shapes.

icing sugar

Powdered sugar, also called confectioners’ sugar, 10X sugar or icing sugar, is a finely ground sugar produced by milling granulated sugar into a powdered state.

two four

Canadian informal a box containing 24 bottles of beer

a case of 24 beers – cans or bottles

Mickey

A half-sized non-EU Standard Liquor Bottle, considered a US metric “pint”. Called a mickey in Canada. -> Alcohol measurements

A 13-ounce bottle of hard alcohol (give or take)

chocolate bars

A chocolate bar (Commonwealth English) or candy bar (some dialects of American English) is a confection containing chocolate, which may also contain layerings or mixtures that include nuts, fruit, caramel, nougat, and wafers. A wide variety of chocolate bar brands are sold. A popular example is a Snickers bar, which consists of nougat mixed with caramel and peanuts, covered in milk chocolate.

Chocolate candy

Molson muscle

beer belly

Kraft Dinner (or KD!)

The product known as Kraft Dinner (KD) in Canada, Kraft Macaroni & Cheese Dinner or Kraft Mac & Cheese in the United States and Australia, and Macaroni Cheese or Cheesey Pasta in the United Kingdom is a nonperishable, packaged dry macaroni and cheese product by Kraft Foods, traditionally cardboard-boxed with dried macaroni pasta and a packet of processed cheese powder. It was first introduced under the Kraft Dinner name simultaneously in both Canada and the U.S. in 1937.

macaroni-and-cheese

freezie

A freezie (Canada), freeze pop (United States), zooper-dooper, juice pop, freezer pop, otter pop, ice-pole, pop stick, icy-pole (Australia), ice pop, popsicle, tip top, lolly (UK), marciano or chupps (Peru), chihiro (Cayman Islands), ice candy (Philippines, Japan), chup-chup, sacolé, geladinho, gelinho, dindim (Brazil), or ais batu Malaysia(Malaysia) is a water-based frozen confection. It is made by freezing flavored liquid such as sugar water, fruit juice or purée inside a plastic casing or tube, either round or flat.

freeze (ice) pop

dépanneur

A convenience store, convenience shop, or corner store is a small retail business that stocks a range of everyday items such as coffee, groceries, snack foods, confectionery, soft drinks, tobacco products, over-the-counter drugs, toiletries, newspapers, and magazines.

A convenience store may also be called a c-store[citation needed], cold store, party store (Michigan), bodega, tienda de barrio (Latin America), carry out, mini-market, mini-mart, konbini (Japan), corner shop, deli or milk bar (Australia), dairy (New Zealand), superette (New Zealand and parts of USA), corner store (many part of English-speaking Canada and New England) depanneur or dep (the last two are loanwords from the French term used in parts of Canada).

convenience store

Rotten Ronnie’s

McDonald’s

booze can

illegal after-hours bar

Caesar

cocktail (not a salad!) similar to a Bloody Mary but made with clamato juice

Clamato juice

clam and tomato juice

poutine

French fries (thin potato chips) covered with cheese curds and gravy

Tortière/tourtière

Meat pie

beavertail/whale’s tail

fried pastry dough smothered in toppings like Nutella chocolate spread

Nanaimo bar

multilayered brownie with icing

Butter tart

Sweet pastry shell tart with a filling of butter, sugar, syrup and egg, baked to get a semi-solid filling and crunchy top

Peameal bacon

Wet-cured, un-smoked back bacon made from trimmed lean boneless pork loin and rolled in cornmeal

Bumbleberry pie

Mixed berry pie (there is no such berry as a bumbleberry!)

Mind Your Habits & Manners!

Canadian tuxedo

informal outfit consisting of a blue denim jacket and blue jeans

Pop

carbonated soft drink/soda

Washroom

Bathroom, restroom, toilet

Queue

Lineup

Tap

faucet

Canuck

Canadian person

kerfuffle

commotion, fuss or disagreement

keener

brown-noser, sycophant

beauty

exceptionally great person

Life’s Good In Canada

Loonie

1-dollar coin

Toonie

2-dollar coin

parkade

parking garage

gas bar

petrol station

chinook

the warm wind that comes over the mountain during winter to melt the snow and raise the temperature

hydro bill

electricity bill

Toque (or tuque)

knitted hat

snowbirds

Canadians who head south to sandy beaches and tropical waters to escape winter

Toboggan

Snow sledge

writing a test

Taking a test, giving an exam

In Canada, the testee writes a test, not the tester!

Just Hanging Out

knapsack

backpack

klicks

kilometres

6ix

Toronto

track pants

Comfortable sweat pants

runners

Comfortable running shoes/sneakers

thongs

Slippers, often worn to the beach

housecoat

Bathrobe or dressing gown

Stag

Bachelor party (US), Stag do (UK)

Stagette

Bachelorette party (US), Hen do (UK)

Darts

Cigarettes (not the bar game!)

Bill

Check (US)

Chesterfield

Sofa, couch

pencil crayons

Coloured pencils

What you sayin’ tonight

What are your plans for tonight? (informal)

True

Okay, fine

Home & Away!

Hang a Larry

Turn left while driving

Hang a Roger

Turn right while driving

dinged

Fined money (not damage to a car in an accident!)

Mountie

member of the highly-respected Royal Canadian Mounted Police (RCMP)

eavestroughs

rain gutters on the roof of a house

garburator

Garbage disposal, usually installed under a kitchen sink

fire hall

Fire station

deke

physical outmanoeuvring of an opponent in ice hockey

stickhandle

skilful controlling of the puck in ice hockey

pogie

On Government welfare assistance

give’r

Go for it, give it your best shot

Elementary school

Grades KG-5

Middle school

Grades 6-8

High school

Grades 9-12

University

After-school college (different from ‘community college’)
Time measured in Years – First Year, Third Year, etc

Grade

School class

拾人牙慧,鹦鹉学舌

书不尽言,言不尽意
言者所以在意,得意而忘言
书到用时方恨少,
事非经过不知难

见者易,学者难
纸上得来终觉浅,
绝知此事要躬行

路不行不到,事不为不成
为事在人,成事在天
人在做,天在看
举头三尺有神明
不畏人知畏己知

谁人背后无人说,
哪个人前不说人,
人无千日好,花无百日红
莫笑他人老,终须还到老
人有八疵,事有四患,不可不察也,
责人之心责己,
恕己之心恕人,
己所不欲,勿施于人

山河大地尚属微尘
而况尘中之尘
事实上我们全都是些集体性人物
我们所特有的东西是微乎其微的
就像我们个人是微乎其微的一样
我们的发展要归功于广大世界千丝万缕的影响

人是条件的产物
不可能是理想的化身
生活可以彻底改变一个人

花开花落春不管
水寒水暖鱼自知
生于忧患,死于安乐
夫大块载我以形,劳我以生,佚我以老,息我以死

世事如棋局局新
生活本来就是由一个接一个意想不到的事件组成的
如果它不是那样的话
那么它就不值得我们去体验

天人合一,物我两忘
天地与我并生
万物与我为一

阴阳于人,不啻于父母
天地者,万物之父母也
巍巍乎,惟天为大
获罪于天,无所祷也
自天佑之,吉无不利

LeetCode - Algorithms - 260. Single Number III

Problem

260. Single Number III

Java

XOR with bitmask

In computer science, a mask or bitmask is data that is used for bitwise operations, particularly in a bit field. Using a mask, multiple bits in a byte, nibble, word etc. can be set either on, off or inverted from on to off (or vice versa) in a single bitwise operation.

A bit mask is a predefined set of bits that is used to select which specific bits will be modified by subsequent operations.

the bit mask blocks the bitwise operators from touching bits we don’t want modified, and allows access to the ones we do want modified.

© https://leetcode.com/problems/single-number-iii/discuss/982092/Python3-XOR-with-bitmask

© https://www.bookstack.cn/read/solve-leetcode-problems/problems-Single%20Number%20III.md

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public int[] singleNumber(int[] nums) {
int xorResult = 0, firstNum = 0, secondNum = 0;
for (int num : nums) {
xorResult ^= num;
}

int bitMask = xorResult & (~xorResult + 1);

for (int num : nums) {
if ((bitMask & num) != 0)
firstNum ^= num;
else
secondNum ^= num;
}

return new int[]{firstNum, secondNum};
}
}

Submission Detail

  • 32 / 32 test cases passed.
  • Runtime: 1 ms, faster than 96.24% of Java online submissions for Single Number III.
  • Memory Usage: 42 MB, less than 5.92% of Java online submissions for Single Number III.

Mask (computing)

Quotes - Isaac Newton

Nature and nature’s laws lay hid in night;
God said “Let Newton be” and all was light.
(Alexander Pope)

It could not last; the Devil shouting “Ho!
Let Einstein be!” restored the status quo.
(J. C. Squire)


Plato is my friend — Aristotle is my friend — but my greatest friend is truth.

If I have seen further it is by standing on the shoulders of giants.

tis due to nothing but industry and a patient thought.

I have not been able to discover the cause of those properties of gravity from phenomena, and I frame no hypotheses; for whatever is not deduced from the phenomena is to be called a hypothesis, and hypotheses, whether metaphysical or physical, whether of occult qualities or mechanical, have no place in experimental philosophy.

To explain all nature is too difficult a task for any one man or even for any one age. ‘Tis much better to do a little with certainty, & leave the rest for others that come after you, than to explain all things by conjecture without making sure of any thing.

I keep the subject constantly before me, and wait ‘till the first dawnings open slowly, by little and little, into a full and clear light.

I do not know what I may appear to the world, but to myself I seem to have been only like a boy playing on the sea-shore, and diverting myself in now and then finding a smoother pebble or a prettier shell than ordinary, whilst the great ocean of truth lay all undiscovered before me.

In default of any other proof, the thumb would convince me of the existence of a God.

It is the perfection of God’s works that they are all done with the greatest simplicity. He is the God of order and not of confusion.

As in Mathematicks, so in Natural Philosophy, the Investigation of difficult Things by the Method of Analysis, ought ever to precede the Method of Composition.

By this way of Analysis we may proceed from Compounds to Ingredients, and from Motions to the Forces producing them; and in general, from Effects to their Causes, and from particular Causes to more general ones, till the Argument end in the most general. This is the Method of Analysis: and the Synthesis consists in assuming the Causes discover’d, and establish’d as Principles, and by them explaining the Phænomena proceeding from them, and proving the Explanations.

Godliness consists in the knowledge love & worship of God, Humanity in love, righteousness & good offices towards man.


Isaac Newton, a posthumous child, born with no father on Christmas Day 1642, was, as Maynard Keynes has aptly written, “the last wonder child to whom the Magi could do sincere and appropriate homage.”

One of the most remarkable aspects of Newton’s most remarkable life is the explosive outburst of his genius. He was not an infant prodigy; and it is probable that when he went to Cambridge in 1661, he knew little more than elementary arithmetic. And it must be remembered that the new outlook on scientific thought that we associate with the names of Galileo, Kepler, and Descartes had hardly yet penetrated the walls of Oxford and Cambridge. Nevertheless, by 1664, when Newton was in his twenty-third year, his genius seems to have flowered. Thus, Newton recalled in his old age that he had “found the method of Infinite Series at such time (1664-65).”

By the summer of 1665, when Cambridge was evacuated on account of the plague and Newton had gone to Woolsthorpe, his genius was fully in flower. It manifested itself in a manner unsurpassed in the history of scientific thought.

An account of a philosophical discovery – which I doubt not but will prove much more grateful than the communication of that instrument, being in my judgement the oddest, if not the most considerable detection, which has hitherto been made in the operation of nature. (January 18, 1672)

I should like to draw your attention especially to the words, “the oddest, if not the most considerable detection.” This is the first and the only time that Newton expresses a trace of enthusiasm with respect to any of his discoveries.

By now Newton’s mathematical genius seems to have been fully aroused, and Newton appears to have been caught in its grip. Newton now entered upon a period of the most intense mathematical activity. Against his will and against his preferences, Newton seems to have been propelled inexorably forward, by the pressure of his own genius, till, at last, he had accomplished the greatest intellectual feat of his life, the greatest intellectual feat in all of science.

By Newton’s own account, he began writing the Principia towards the end of December 1684, and he sent the completed manuscript of all three Books of the Principia to the Royal Society in May 1686, that is, in seventeen months. He had solved two of the propositions in the first Book in 1679, and he had also proved eight of the propositions in the second Book in June and July 1685. There are ninety-eight propositions in the first Book; fifty-three in the second; and forty-two in the third. By far the larger proportion of them was, therefore, enunciated and proved during the seventeen consecutive months that Newton was at work on the three Books. It is this rapidity of execution, besides the monumental scale of the whole work, that makes this achievement incomparable. If the problems enunciated in the Principia were the results of a lifetime of thought and work, Newton’s position in science would still be unique. But that all these problems should have been enunciated, solved, and arranged in logical sequence in seventeen months is beyond human comprehension. It can be accepted only because it is a fact: it just happens to be so!

It is only when we observe the scale of Newton’s achievement that comparisons, which have sometimes been made with other men of science, appear altogether inappropriate both with respect to Newton and with respect to the others. In fact, only in juxtaposition with Shakespeare and Beethoven is the consideration of Newton appropriate.

No account of Newton’s life, however brief, can omit some indication of the manner of man he was. The subject is a complex and a controversial one. But this much can fairly be said: Newton seems to have been remarkably insensitive: impervious to the arts, tactless, and with no real understanding of others.

Newton’s most remarkable gift was probably his powers of concentration. As Keynes wrote:

His peculiar gift was the power of holding continuously in his mind a purely mental problem until he had seen straight through it. I fancy his pre-eminence is due to his muscles of intuition being the strongest and most enduring with which a man has ever been gifted… I believe that Newton could hold a problem in his mind for hours and days and weeks until it surrendered to him its secret.

Besides, as De Morgan has said, he was:

…So happy in his conjectures as to seem to know more than he could possibly have any means of proving.

But the central paradox of Newton’s life is that he deliberately and systematically ignored his supreme mathematical genius and through most of his life neglected the one activity for which he was gifted beyond any man. This paradox can be resolved only if we realize that Newton simply did not consider science and mathematics as of any great importance;

I do not know what I may appear to the world, but to myself I seem to have been only like a boy playing on the sea-shore, and diverting myself in now and then finding a smoother pebble or a prettier shell than ordinary, whilst the great ocean of truth lay all undiscovered before me.

In view of Newton’s insensitiveness to others, doubts have sometimes been raised about the sincerity of this statement. I do not believe that such doubts are warranted: only someone, like Newton, who can view knowledge from his height, can have the vision of an “ocean of undiscovered truth.” As an ancient proverb of India says, “Only the wise can plumb the wells of wisdom.”

(Shakespeare, Newton, and Beethoven: Or, Patterns of Creativity, a talk by Subrahmanyan Chandrasekhar)


LeetCode - Algorithms - 674. Longest Continuous Increasing Subsequence

Problem

674. Longest Continuous Increasing Subsequence

Java

Sliding Window

Sliding Window problems are a subset of dynamic programming problems, though the approach to solving them is quite different from the one used in solving tabulation or memoization problems.

© Approach 1: Sliding Window

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public int findLengthOfLCIS(int[] nums) {
int maxLen = 0;
int anchor = 0;
for (int i = 0; i < nums.length; i++) {
if (i > 0 && nums[i] <= nums[i - 1]) anchor = i;
maxLen = Math.max(maxLen, i - anchor + 1);
}
return maxLen;
}
}

Submission Detail

  • 36 / 36 test cases passed.
  • Runtime: 1 ms, faster than 98.29% of Java online submissions for Longest Continuous Increasing Subsequence.
  • Memory Usage: 39.7 MB, less than 70.15% of Java online submissions for Longest Continuous Increasing Subsequence.

my solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public int findLengthOfLCIS(int[] nums) {
final int N = nums.length;
if (N < 2)
return N;
int len = 1, tempLen = 1;
for (int i = 1; i < N; i++) {
if (nums[i] > nums[i - 1]) {
tempLen++;
} else {
if (tempLen > len)
len = tempLen;
tempLen = 1;
}
}
if (tempLen > len)
len = tempLen;
return len;
}
}

Submission Detail

  • 36 / 36 test cases passed.
  • Runtime: 1 ms, faster than 98.29% of Java online submissions for Longest Continuous Increasing Subsequence.
  • Memory Usage: 39.9 MB, less than 41.25% of Java online submissions for Longest Continuous Increasing Subsequence.

What we're learning from online education - Daphne Koller - TEDGlobal 2012 - Transcript

Like many of you, I’m one of the lucky people. I was born to a family where education was pervasive. I’m a third-generation PhD, a daughter of two academics. In my childhood, I played around in my father’s university lab. So it was taken for granted that I attend some of the best universities, which in turn opened the door to a world of opportunity.

Unfortunately, most of the people in the world are not so lucky. In some parts of the world, for example, South Africa, education is just not readily accessible. In South Africa, the educational system was constructed in the days of apartheid for the white minority. And as a consequence, today there is just not enough spots for the many more people who want and deserve a high quality education. That scarcity led to a crisis in January of this year at the University of Johannesburg. There were a handful of positions left open from the standard admissions process, and the night before they were supposed to open that for registration, thousands of people lined up outside the gate in a line a mile long, hoping to be first in line to get one of those positions. When the gates opened, there was a stampede, and 20 people were injured and one woman died. She was a mother who gave her life trying to get her son a chance at a better life.

But even in parts of the world like the United States where education is available, it might not be within reach. There has been much discussed in the last few years about the rising cost of health care. What might not be quite as obvious to people is that during that same period the cost of higher education tuition has been increasing at almost twice the rate, for a total of 559 percent since 1985. This makes education unaffordable for many people.

Finally, even for those who do manage to get the higher education, the doors of opportunity might not open. Only a little over half of recent college graduates in the United States who get a higher education actually are working in jobs that require that education. This, of course, is not true for the students who graduate from the top institutions, but for many others, they do not get the value for their time and their effort.

Tom Friedman, in his recent New York Times article, captured, in the way that no one else could, the spirit behind our effort. He said the big breakthroughs are what happen when what is suddenly possible meets what is desperately necessary. I’ve talked about what’s desperately necessary. Let’s talk about what’s suddenly possible.

What’s suddenly possible was demonstrated by three big Stanford classes, each of which had an enrollment of 100,000 people or more. So to understand this, let’s look at one of those classes, the Machine Learning class offered by my colleague and cofounder Andrew Ng. Andrew teaches one of the bigger Stanford classes. It’s a Machine Learning class, and it has 400 people enrolled every time it’s offered. When Andrew taught the Machine Learning class to the general public, it had 100,000 people registered. So to put that number in perspective, for Andrew to reach that same size audience by teaching a Stanford class, he would have to do that for 250 years. Of course, he’d get really bored.

So, having seen the impact of this, Andrew and I decided that we needed to really try and scale this up, to bring the best quality education to as many people as we could. So we formed Coursera, whose goal is to take the best courses from the best instructors at the best universities and provide it to everyone around the world for free. We currently have 43 courses on the platform from four universities across a range of disciplines, and let me show you a little bit of an overview of what that looks like.

(Video) Robert Ghrist: Welcome to Calculus.

Ezekiel Emanuel: Fifty million people are uninsured.

Scott Page: Models help us design more effective institutions and policies. We get unbelievable segregation.

Scott Klemmer: So Bush imagined that in the future, you’d wear a camera right in the center of your head.

Mitchell Duneier: Mills wants the student of sociology to develop the quality of mind …

RG: Hanging cable takes on the form of a hyperbolic cosine.

Nick Parlante: For each pixel in the image, set the red to zero.

Paul Offit: … Vaccine allowed us to eliminate polio virus.

Dan Jurafsky: Does Lufthansa serve breakfast and San Jose? Well, that sounds funny.

Daphne Koller: So this is which coin you pick, and this is the two tosses.

Andrew Ng: So in large-scale machine learning, we’d like to come up with computational …

(Applause)

DK: It turns out, maybe not surprisingly, that students like getting the best content from the best universities for free. Since we opened the website in February, we now have 640,000 students from 190 countries. We have 1.5 million enrollments, 6 million quizzes in the 15 classes that have launched so far have been submitted, and 14 million videos have been viewed.

But it’s not just about the numbers, it’s also about the people. Whether it’s Akash, who comes from a small town in India and would never have access in this case to a Stanford-quality course and would never be able to afford it. Or Jenny, who is a single mother of two and wants to hone her skills so that she can go back and complete her master’s degree. Or Ryan, who can’t go to school, because his immune deficient daughter can’t be risked to have germs come into the house, so he couldn’t leave the house. I’m really glad to say – recently, we’ve been in correspondence with Ryan – that this story had a happy ending. Baby Shannon – you can see her on the left – is doing much better now, and Ryan got a job by taking some of our courses.

So what made these courses so different? After all, online course content has been available for a while. What made it different was that this was real course experience. It started on a given day, and then the students would watch videos on a weekly basis and do homework assignments. And these would be real homework assignments for a real grade, with a real deadline. You can see the deadlines and the usage graph. These are the spikes showing that procrastination is global phenomenon.

(Laughter)

At the end of the course, the students got a certificate. They could present that certificate to a prospective employer and get a better job, and we know many students who did. Some students took their certificate and presented this to an educational institution at which they were enrolled for actual college credit. So these students were really getting something meaningful for their investment of time and effort.

Let’s talk a little bit about some of the components that go into these courses. The first component is that when you move away from the constraints of a physical classroom and design content explicitly for an online format, you can break away from, for example, the monolithic one-hour lecture. You can break up the material, for example, into these short, modular units of eight to 12 minutes, each of which represents a coherent concept. Students can traverse this material in different ways, depending on their background, their skills or their interests. So, for example, some students might benefit from a little bit of preparatory material that other students might already have. Other students might be interested in a particular enrichment topic that they want to pursue individually. So this format allows us to break away from the one-size-fits-all model of education, and allows students to follow a much more personalized curriculum.

Of course, we all know as educators that students don’t learn by sitting and passively watching videos. Perhaps one of the biggest components of this effort is that we need to have students who practice with the material in order to really understand it. There’s been a range of studies that demonstrate the importance of this. This one that appeared in Science last year, for example, demonstrates that even simple retrieval practice, where students are just supposed to repeat what they already learned gives considerably improved results on various achievement tests down the line than many other educational interventions.

We’ve tried to build in retrieval practice into the platform, as well as other forms of practice in many ways. For example, even our videos are not just videos. Every few minutes, the video pauses and the students get asked a question.

(Video) SP: … These four things. Prospect theory, hyperbolic discounting, status quo bias, base rate bias. They’re all well documented. So they’re all well documented deviations from rational behavior.

DK: So here the video pauses, and the student types in the answer into the box and submits. Obviously they weren’t paying attention.

(Laughter)

So they get to try again, and this time they got it right. There’s an optional explanation if they want. And now the video moves on to the next part of the lecture. This is a kind of simple question that I as an instructor might ask in class, but when I ask that kind of a question in class, 80 percent of the students are still scribbling the last thing I said, 15 percent are zoned out on Facebook, and then there’s the smarty pants in the front row who blurts out the answer before anyone else has had a chance to think about it, and I as the instructor am terribly gratified that somebody actually knew the answer. And so the lecture moves on before, really, most of the students have even noticed that a question had been asked. Here, every single student has to engage with the material.

And of course these simple retrieval questions are not the end of the story. One needs to build in much more meaningful practice questions, and one also needs to provide the students with feedback on those questions. Now, how do you grade the work of 100,000 students if you do not have 10,000 TAs? The answer is, you need to use technology to do it for you. Now, fortunately, technology has come a long way, and we can now grade a range of interesting types of homework. In addition to multiple choice and the kinds of short answer questions that you saw in the video, we can also grade math, mathematical expressions as well as mathematical derivations. We can grade models, whether it’s financial models in a business class or physical models in a science or engineering class and we can grade some pretty sophisticated programming assignments.

Let me show you one that’s actually pretty simple but fairly visual. This is from Stanford’s Computer Science 101 class, and the students are supposed to color-correct that blurry red image. They’re typing their program into the browser, and you can see they didn’t get it quite right, Lady Liberty is still seasick. And so, the student tries again, and now they got it right, and they’re told that, and they can move on to the next assignment. This ability to interact actively with the material and be told when you’re right or wrong is really essential to student learning.

Now, of course we cannot yet grade the range of work that one needs for all courses. Specifically, what’s lacking is the kind of critical thinking work that is so essential in such disciplines as the humanities, the social sciences, business and others. So we tried to convince, for example, some of our humanities faculty that multiple choice was not such a bad strategy. That didn’t go over really well.

So we had to come up with a different solution. And the solution we ended up using is peer grading. It turns out that previous studies show, like this one by Saddler and Good, that peer grading is a surprisingly effective strategy for providing reproducible grades. It was tried only in small classes, but there it showed, for example, that these student-assigned grades on the y-axis are actually very well correlated with the teacher-assigned grade on the x-axis. What’s even more surprising is that self-grades, where the students grade their own work critically – so long as you incentivize them properly so they can’t give themselves a perfect score – are actually even better correlated with the teacher grades. And so this is an effective strategy that can be used for grading at scale, and is also a useful learning strategy for the students, because they actually learn from the experience. So we now have the largest peer-grading pipeline ever devised, where tens of thousands of students are grading each other’s work, and quite successfully, I have to say.

But this is not just about students sitting alone in their living room working through problems. Around each one of our courses, a community of students had formed, a global community of people around a shared intellectual endeavor. What you see here is a self-generated map from students in our Princeton Sociology 101 course, where they have put themselves on a world map, and you can really see the global reach of this kind of effort.

Students collaborated in these courses in a variety of different ways. First of all, there was a question and answer forum, where students would pose questions, and other students would answer those questions. And the really amazing thing is, because there were so many students, it means that even if a student posed a question at 3 o’clock in the morning, somewhere around the world, there would be somebody who was awake and working on the same problem. And so, in many of our courses, the median response time for a question on the question and answer forum was 22 minutes. Which is not a level of service I have ever offered to my Stanford students.

(Laughter)

And you can see from the student testimonials that students actually find that because of this large online community, they got to interact with each other in many ways that were deeper than they did in the context of the physical classroom. Students also self-assembled, without any kind of intervention from us, into small study groups. Some of these were physical study groups along geographical constraints and met on a weekly basis to work through problem sets. This is the San Francisco study group, but there were ones all over the world. Others were virtual study groups, sometimes along language lines or along cultural lines, and on the bottom left there, you see our multicultural universal study group where people explicitly wanted to connect with people from other cultures.

There are some tremendous opportunities to be had from this kind of framework. The first is that it has the potential of giving us a completely unprecedented look into understanding human learning. Because the data that we can collect here is unique. You can collect every click, every homework submission, every forum post from tens of thousands of students. So you can turn the study of human learning from the hypothesis-driven mode to the data-driven mode, a transformation that, for example, has revolutionized biology. You can use these data to understand fundamental questions like, what are good learning strategies that are effective versus ones that are not? And in the context of particular courses, you can ask questions like, what are some of the misconceptions that are more common and how do we help students fix them?

So here’s an example of that, also from Andrew’s Machine Learning class. This is a distribution of wrong answers to one of Andrew’s assignments. The answers happen to be pairs of numbers, so you can draw them on this two-dimensional plot. Each of the little crosses that you see is a different wrong answer. The big cross at the top left is where 2,000 students gave the exact same wrong answer. Now, if two students in a class of 100 give the same wrong answer, you would never notice. But when 2,000 students give the same wrong answer, it’s kind of hard to miss. So Andrew and his students went in, looked at some of those assignments, understood the root cause of the misconception, and then they produced a targeted error message that would be provided to every student whose answer fell into that bucket, which means that students who made that same mistake would now get personalized feedback telling them how to fix their misconception much more effectively.

So this personalization is something that one can then build by having the virtue of large numbers. Personalization is perhaps one of the biggest opportunities here as well, because it provides us with the potential of solving a 30-year-old problem. Educational researcher Benjamin Bloom, in 1984, posed what’s called the 2 sigma problem, which he observed by studying three populations. The first is the population that studied in a lecture-based classroom. The second is a population of students that studied using a standard lecture-based classroom, but with a mastery-based approach, so the students couldn’t move on to the next topic before demonstrating mastery of the previous one. And finally, there was a population of students that were taught in a one-on-one instruction using a tutor. The mastery-based population was a full standard deviation, or sigma, in achievement scores better than the standard lecture-based class, and the individual tutoring gives you 2 sigma improvement in performance.

To understand what that means, let’s look at the lecture-based classroom, and let’s pick the median performance as a threshold. So in a lecture-based class, half the students are above that level and half are below. In the individual tutoring instruction, 98 percent of the students are going to be above that threshold. Imagine if we could teach so that 98 percent of our students would be above average. Hence, the 2 sigma problem.

Because we cannot afford, as a society, to provide every student with an individual human tutor. But maybe we can afford to provide each student with a computer or a smartphone. So the question is, how can we use technology to push from the left side of the graph, from the blue curve, to the right side with the green curve? Mastery is easy to achieve using a computer, because a computer doesn’t get tired of showing you the same video five times. And it doesn’t even get tired of grading the same work multiple times, we’ve seen that in many of the examples that I’ve shown you. And even personalization is something that we’re starting to see the beginnings of, whether it’s via the personalized trajectory through the curriculum or some of the personalized feedback that we’ve shown you. So the goal here is to try and push, and see how far we can get towards the green curve.

So, if this is so great, are universities now obsolete? Well, Mark Twain certainly thought so. He said that, “College is a place where a professor’s lecture notes go straight to the students’ lecture notes, without passing through the brains of either.”

(Laughter)

I beg to differ with Mark Twain, though. I think what he was complaining about is not universities but rather the lecture-based format that so many universities spend so much time on. So let’s go back even further, to Plutarch, who said that, “The mind is not a vessel that needs filling, but wood that needs igniting.” And maybe we should spend less time at universities filling our students’ minds with content by lecturing at them, and more time igniting their creativity, their imagination and their problem-solving skills by actually talking with them.

So how do we do that? We do that by doing active learning in the classroom. So there’s been many studies, including this one, that show that if you use active learning, interacting with your students in the classroom, performance improves on every single metric – on attendance, on engagement and on learning as measured by a standardized test. You can see, for example, that the achievement score almost doubles in this particular experiment. So maybe this is how we should spend our time at universities.

So to summarize, if we could offer a top quality education to everyone around the world for free, what would that do? Three things. First it would establish education as a fundamental human right, where anyone around the world with the ability and the motivation could get the skills that they need to make a better life for themselves, their families and their communities.

Second, it would enable lifelong learning. It’s a shame that for so many people, learning stops when we finish high school or when we finish college. By having this amazing content be available, we would be able to learn something new every time we wanted, whether it’s just to expand our minds or it’s to change our lives.

And finally, this would enable a wave of innovation, because amazing talent can be found anywhere. Maybe the next Albert Einstein or the next Steve Jobs is living somewhere in a remote village in Africa. And if we could offer that person an education, they would be able to come up with the next big idea and make the world a better place for all of us.

Thank you very much.