海外TECH |
DEV Community |
Big O notation basics made dead simple |
https://dev.to/heyjtk/big-o-notation-basics-made-dead-simple-1c9m
|
Big O notation basics made dead simple A brief conversation about big OTo be honest with you when I first got into programming I procrastinated learning Big O for quite a while out of intimidation and this article is really for anyone out there who feels similar I don t know if it will help for me to say that most of it is common sense and the math doesn t get much harder than multiplication But just in case I will add some visuals to make this as non miserable as possible The graphics are super silly but honestly that helps me remember things If I were to give you the simplest version possible of the idea behind Big O notation or the time complexity of how your code runs it would be something like this basic operations are the most efficientrepeated operations loops can be more of a worry for efficiencynested loops are among the biggest worries for efficiencyHonestly that s the basics Not too terrible right There s also a whole category of things you never have to think about when figuring out the performance of your code You can consider them “Freebies They include basic math addition and subtractionassigning variablesif else conditionsdeclaring a functioncalling a function at face value changing variablesIf I had to sum the concept of Big O up in simplest terms imaginable loops are pretty much all we are worried about I know when I realized that I felt a lot less intimidated A note before we begin This is meant to be the absolute basics for people who think Big O notation sounds like archaic rituals There are more nuances and more descriptors than I ve included here Whenever there is a chance to take clarity vs greater detail I have chosen clarity This post is for folks a few months into programming who need basic actionable info This is part of a larger series I m writing on live coding interviews so give that a read as well To explain some of these let s pretend that in my free time I like to go on scavenger hunts My friends make the rules for these hunts and some are less challenging than others Sidebar some people really do this There is a hobby called geocaching that is pretty much real life treasure hunting You can read about that here if you are curious My examples are too silly to conform to really geocaching though so I ll stick with the term scavenger hunt Part I Constant time or O ️Jamie sends me on a treasure hunt to retrieve a pen from a certain address on Chestnut street I have one address so only need to go to one house easy peasy This is an example of what we would call “constant time Whether the scavenger hunt was for a pen or something else I m only knocking on one door in this scenario and it will not change This is considered a very positive state for algorithm performance the most optimal actually An example of a constant operation would be retrieving a value from a JavaScript object const person name Ann hobbies drawing programming pet dog console log person name Because JavaScript objects are an example of a hash it is very performant to look up some value in an object It is a perfect analog to having an exact address and being able to go straight to it without searching further Regardless of what is inside the step of retrieving the item is considered to run in constant time For this reason objects hash data structures are often your friend in code challenges Sometimes getting arrays into an object format can be hugely helpful for good performance in these types of challenges We call this constant time O in Big O notation Part Logarithmic time or O log N My friend Jake has set me on a trickier task There is a new development being built near me but they have not added visible street signs If I walk up to the houses though They have notated the address on beams by the front door I don t really want to have to walk up to each house individually but after thinking about it I realize Jake has shared that the home address numbers increase as you progress down the street I don t know the starting number as the road continues a ways past this cul de sac in the opposite direction so I m not sure what the lowest house number is But I do know I m looking for I realize that if I start in the middle of the street I ll see if the address is lower or higher than what I m looking for and can knock out half the houses on the block so I don t have to search those I see the house in the middle is so all the houses to the right of this one would have house numbers too high for what I m looking for So I can cross off the house I walked up to and all the houses to the right because they would have even higher numbers Now in a normal world these houses would all be regular and I could just count my way to the correct one but I see some empty dirt lots and can t tell if those will also become homes or are for landscaping or parks Because I m not entirely sure what are lots I am not sure just counting my way down the street to the correct house would work So I decide to go with my “pick from the middle approach again and that way can at least cross of half of the remaining section of the street based on if the house is numbered too high or low For this reason I pick the middle house again of my remaining three houses Whaddya know That s the correct one If you want to think of my “treasure hunt algorithm the end result is pretty good I wound up only having to walk up to two houses even though there were seven on the street In terms of how much work I had to do to succeed at this task my approach meant that the remaining houses to search would have been cut in half each time I walked up to one We call the performance when you cut the result set each time logarithmic performance and after constant time O it is as ideal as you can get Even though you have a result set of the operations you perform could be as low as If you don t remember much about logarithms from math that s honestly fine all you need to know is that its a GREAT performance for an algorithm to have because you are cutting your result set down significantly each time In Big O language we write logarithmic performance as O log n If you are worried about memorizing the big o descriptor simply calling it “logarithmic time in an interview is perfectly ok And if all you need to know is that logarithmic time means that each pass you cut your results down potentially by half it is pretty easy to recognize this when you are doing it As a side bar my scavenger hunt example is an example of a binary search algorithm Not too bad right Just pick from the middle over and over It is a great algorithm to use if you know your results are already in some type of order Part Linear time or O n My friend Jess on hearing how much work I ve been putting into these scavenger hunts takes pity on me Lucky for me it happens to be October st and she assigns me the task of trick or treating My treasure hunt is to get one piece of candy from every house on Sycamore street In this somewhat deliberately messy graphic you can see how much work this is compared to my last task This is what we call in Big O “linear time aka a loop aka simple multiplication My task is multiplied by the number of houses On a bigger street that might be trips My work increases in a linear fashion based on what street I m on and how many houses it has For big O linear time is a good algorithm performance in many cases Not as good as the first two we covered but normally a code challenge you would receive in an interview is complex enough that there is a reasonable chance loops will be required We write this as O n with “n being basically what you are multiplying by or how many loops you d have to do Part Quadratic and cubic timeMy last pal Andrew is really devious and sets me on the hardest treasure hunt yet He sets me off on main street and says that for every house on the street I need to collect a strand of grass a rock a weed of some type a leaf and flower Very quickly I m up to individual tasks since I have five things to do for each of five houses You can easily see if we put this to numbers I have x tasks or This is what we call quadratic time In programming this means one thing nested loops Each nested layer is adding an exponent If my friend said this treasure hunt was for all houses on Main Street Carver Street Guess Road Roxboro Road and Mangum Street it would be each task for each house for each street also known as x x or We d call that cubic time My example is pretty manageable still but in real life programming we are looking at way larger numbers than this See how the tasks balloon Base numberTasks Tasks Tasks This is maybe the most important area I can talk to you about It comes up the most in my job and the most programming You can quickly see why it gets important fast You will notice that that first row where your base number is can quickly get into more operations than that last row with a starting number of a million if they are not careful about nested looping Someone with a data set a million large can have a program doing less work than someone with that data set of records all depending on how careful they are with nested looping Most of the finer points that come up for me in code challenges are if I can get something from a loop to constant time and then if I can get something from a nested loop to a single loop So from cubic time O n to quadratic time O n We also have a more general word to represent situations where the exponent is going to be to the power of n exponential time O n Part What this may look likeLet s say we got the following code challenge Given an array of unique integers and a target number determine if any two numbers in the array when added together would equal the target If that condition is met return the array position of the two numbers You cannot reuse a number at a single index position So array could maketarget number but array could not since it would require reusing thearray value at position array Example given array and target number you would return an answer since at array you have number at array you have number and added together they make Example given array and target number you would return false because the condition can not be met This is a paraphrase of a Leetcode problem where below it asks follow up question “Can you get the time complexity below O n The fact that they ask is a good hint that we might But for a very new programmer the obvious way to solve this problem might be something like this You can also run the code yourself here You can see that very quickly the exponential logic catches up with us and we have quite a few individual task calls in this method Going back to what I said before about trying to get things into shape where you can take advantage of constant time and linear time I m going to use all the same test cases but rewrite this function in a way with better Big O BTW this is illustrative maybe not precisely how I would solve this problem so don t come for me in the comments lol Hashes are really your friend in these kind of problems So when I iterate over my list I m going to make a JavaScript object where each key is what the list item would need to be added with to reach the target number and the value would be the index I found this item at Example given target number and list my JS object would look like this first array item is we d need to find a to make its at index second array item is we d need to find a to make its at index so on and so forth So with this object it means I don t need to do a nested loop I can do another regular loop so linear time and just check if the current list item is one of the keys for this Javascript object If it is I ve found a matching pair whose sum is the target number I have saved the index where the first number was located as the key value so I already have that handy and then can just return the index of the list item I am on in my second loop You can also play with this code here I used the same test cases and you can see got the same results But with my nested loop approach the worst performance we saw was gt operations and by not nesting my loops it is only THIRTY That s pretty amazing And it wasn t too hard once you get used to thinking this way to extract the nested loop behavior and find another way Visualizing what we ve learnedOne great way to drive home how these perform is to look at a graph of performance I grabbed this one from this website Another fun noteYou may wonder when looking at the problem above is the Big O notation O n since we are looping twice If a loop is O n we have done that twice once to build the JavaScript object and a second time to process the list again and see if we have two numbers that will sum to the target number If you remember me saying that all we care about is loops mainly add an asterisk here to say we care about the greatest magnitude of operation present in the problem What does that mean If you have a loop in your program with performance O n and later in the code you have a nested loop with performance O n we call the big O simply O n the exponent is the behavior of the highest order of magnitude in the program aka the biggest worry So we drop the lesser oneIf you have a nested loop running at O n and later on a triple nested loop running O n we would simplify that to cubic time That triple nested loop is the highest order of magnitude thing going on in the code so we simplify to call it O n If you think about it it is more fair to do it this way Almost everything you will write will have some operations that are O but it is almost never accurate to say the overall performance of a program is O If it has a single loop that statement will not be accurate ConclusionThere are some other types of Big O notation we could cover but these are the ones I see most commonly and they should get a new programmer pretty far in code challenges Even if you don t feel super into math concepts remembering that loops are the biggest thing you need to worry about is I think easy enough advice that anyone can keep in mind and it really does help you in keeping performance in mind no matter what level of coding expertise you have Also here are some other great resources Big O Notation with examplesAlgorithms in plain english time complexity and Big O Notation |
2022-09-02 19:06:38 |
海外TECH |
Engadget |
Controversial social media app Parler is back on the Google Play Store |
https://www.engadget.com/parler-app-return-to-android-play-store-191902824.html?src=rss
|
Controversial social media app Parler is back on the Google Play StoreParler the app that s largely associated with Donald Trump supporters conservatives and far right extremists is once again available for download via the Google Play Store Billing itself as a quot free speech network quot Parler was banned and removed from the Android app store in January after the US Capitol insurrection A Google spokesperson said at the time that the removal was due to the app s lack of quot moderation policies and enforcement that remove egregious content like posts that incite violence quot nbsp A Google spokesperson said quot As we ve long stated apps are able to appear on Google Play provided they comply with Play s developer policies All apps on Google Play that feature user generated content UGC are required to implement robust moderation practices that prohibit objectionable content provide an in app system for reporting objectionable UGC take action against that UGC where appropriate and remove or block abusive users who violate the app s terms of use and or user policy quot Parler has made substantial modifications to its app to comply with Google s policies Bloomberg and Axios have reported that the apps developers have implemented policies to moderate content and remove posts that incite violence which made it compliant with Google s requirements Despite its suspension and delisting from the Android app store people could still download Parler from the company s website and continue to use it Parler was reinstated to the iOS app store in May this year after modifying its AI based moderation tool to hide content it identifies as quot hate quot Donald Trump s quot Truth Social quot has been available on the iOS store since February though it has yet to launch on Android Google reportedly has yet to approve that app due to concerns over its violations of standards and inadequate moderation policies |
2022-09-02 19:19:02 |
海外科学 |
NYT > Science |
Humpback Whales Pass Their Songs Across Oceans |
https://www.nytimes.com/2022/08/30/science/humpback-whale-songs-cultural-evolution.html
|
cultural |
2022-09-02 19:08:37 |
ビジネス |
ダイヤモンド・オンライン - 新着記事 |
英国新首相「ほぼ確実」のトラス外相、勝利なら為替市場はポンド買いで反応か - 政策・マーケットラボ |
https://diamond.jp/articles/-/309118
|
為替市場 |
2022-09-03 04:55:00 |
ビジネス |
ダイヤモンド・オンライン - 新着記事 |
「文春砲」に撃たれた坂本孝が、稲盛和夫に叱られた恐怖と感謝の45分【見逃し配信・追悼・稲盛和夫氏】 - 見逃し配信 |
https://diamond.jp/articles/-/309065
|
名誉会長 |
2022-09-03 04:50:00 |
ビジネス |
ダイヤモンド・オンライン - 新着記事 |
松下幸之助氏が新入社員の話にも聞き入った理由、上司に必要な「聞く力」の真髄 - 小宮一慶の週末経営塾 |
https://diamond.jp/articles/-/309071
|
小宮一慶 |
2022-09-03 04:45:00 |
ビジネス |
ダイヤモンド・オンライン - 新着記事 |
富裕層の相続税対策に「不動産クラウドファンディング」は有効か? - News&Analysis |
https://diamond.jp/articles/-/308938
|
newsampampanalysis |
2022-09-03 04:40:00 |
ビジネス |
ダイヤモンド・オンライン - 新着記事 |
面倒な防災、楽しみながら備える方法とは?キャンプや散歩が災害対策にも - 井の中の宴 武藤弘樹 |
https://diamond.jp/articles/-/309116
|
意識が高い |
2022-09-03 04:35:00 |
ビジネス |
ダイヤモンド・オンライン - 新着記事 |
東大卒クイズ王が教える、独学でモチベーションをどう維持させるか - 一生役立つ独学戦略 |
https://diamond.jp/articles/-/308645
|
受験勉強 |
2022-09-03 04:30:00 |
ビジネス |
ダイヤモンド・オンライン - 新着記事 |
沖縄&北海道、現地ガイドの「おすすめ観光地6選」で日本の魅力を再発見 - 地球の歩き方ニュース&レポート |
https://diamond.jp/articles/-/308831
|
地球の歩き方 |
2022-09-03 04:25:00 |
ビジネス |
ダイヤモンド・オンライン - 新着記事 |
医師に聞くサウナの正しい入り方、超高温サウナや水風呂で刺激中毒に? - from AERAdot. |
https://diamond.jp/articles/-/309063
|
fromaeradot |
2022-09-03 04:20:00 |
ビジネス |
ダイヤモンド・オンライン - 新着記事 |
クロノグラフ腕時計「不朽の名作」4選の造形美を愛でる、ロンジン・バルジュー… - 男のオフビジネス |
https://diamond.jp/articles/-/308869
|
造形 |
2022-09-03 04:15:00 |
ビジネス |
ダイヤモンド・オンライン - 新着記事 |
出生前診断の新たな検査法が誕生、従来より「早い・安い・簡単」な方法とは - ヘルスデーニュース |
https://diamond.jp/articles/-/309066
|
出生前診断の新たな検査法が誕生、従来より「早い・安い・簡単」な方法とはヘルスデーニュース胎児に流産リスクを高める遺伝的問題があるかどうかを検査当日のうちに知ることができる、新たな検査法が開発された。 |
2022-09-03 04:10:00 |
ビジネス |
ダイヤモンド・オンライン - 新着記事 |
【ひろゆきが明かす】中学生のときになりたいと決めた「ある理想像」 - 99%はバイアス |
https://diamond.jp/articles/-/308950
|
記事 |
2022-09-03 04:05:00 |
ビジネス |
東洋経済オンライン |
実は「山手線の終点」、田端駅周辺には何がある? アニメの聖地としても再注目「鉄道と文化の町」 | 山手線の過去・現在・未来 | 東洋経済オンライン |
https://toyokeizai.net/articles/-/615182?utm_source=rss&utm_medium=http&utm_campaign=link_back
|
国土交通省 |
2022-09-03 04:30:00 |
コメント
コメントを投稿