Dynamic Algorithms Part 2

          Last week we went over the basics of dynamic algorithms, the definition, and the steps in creating a dynamic program. This week we will walk through an example, we will take a common algorithm and then using our step make it dynamic.

            The algorithm we will be working with is Longest Common Subsequence or LCS for short, this and variations on it are a common leet code and white boarding problem so more likely than not you have seen this or will see this algorithm. The basic problem statement is you have two strings for example “Coward” and “Forward”, and you must create and algorithm that finds the longest subsequence of letters that are matched in both words, in this example it would be “oward”. To get to the LCS you would first check all other subsequences such as “Bas” and so on. The non-dynamic or brute force approach will have an exponential time complexity is it will as it will have overlapping subproblems that will result in inefficiency causing it to run in its worst case when both words have no matches at O() and if you know anything about time complexity this is extremely  slow. Here is a basic recursive version of the algorithm.

def lcs(X, Y, m, n): 
  
    if m == 0 or n == 0: 
       return 0; 
    elif X[m-1] == Y[n-1]: 
       return 1 + lcs(X, Y, m-1, n-1); 
    else: 
       return max(lcs(X, Y, m, n-1), lcs(X, Y, m-1, n)); 
  
  
# Driver program to test the above function 
X = "AGGTAB"
Y = "GXTXAYB"
print "Length of LCS is ", lcs(X , Y, len(X), len(Y)) 

(1)

As you can see this solution is successful at find the LCS, while the code is simple easy to read it is horribly in efficient as it will solve certain parts of the sub problem twice in the recursion tree. This is a great example of a problem to use dynamic programming on as we know DP uses techniques to save results to stop from overlapping subproblems. So, we start on our first step we will identify the sub problem. Luckily, we have already done so in the original version breaking it into sub. We will do this in a bottom up approach, the operations we must do on each LCS word is compare each letter to one another, while also using an array for storing the results to compare to later. Then contain this inside two nested loops as this we will at least need to pass over the strings n times. Here is the DP version of the algorithm.

def lcs(X , Y): 
    # find the length of the strings 
    m = len(X) 
    n = len(Y) 
  
    # declaring the array for storing the dp values 
    L = [[None]*(n+1) for i in xrange(m+1)] 
  
    """Following steps build L[m+1][n+1] in bottom up fashion 
    Note: L[i][j] contains length of LCS of X[0..i-1] 
    and Y[0..j-1]"""
    for i in range(m+1): 
        for j in range(n+1): 
            if i == 0 or j == 0 : 
                L[i][j] = 0
            elif X[i-1] == Y[j-1]: 
                L[i][j] = L[i-1][j-1]+1
            else: 
                L[i][j] = max(L[i-1][j] , L[i][j-1]) 
  
    # L[m][n] contains the length of LCS of X[0..n-1] & Y[0..m-1] 
    return L[m][n] 
#end of function lcs 
  
  
# Driver program to test the above function 
X = "AGGTAB"
Y = "GXTXAYB"
print "Length of LCS is ", lcs(X, Y) 
  
# This code is contributed by Nikhil Kumar Singh 

(1)

As you can see this version is much quicker and runs in worst case in O(). Hope this run down of the dynamic version of LCS was helpful.

Sources:

  1. https://www.geeksforgeeks.org/longest-common-subsequence-dp-4/

Dynamic Programming

          Dynamic programming is an algorithmic technique of simplifying a com-plex problem into smaller simpler subproblems. This might sound familiar, this definition is awfully close to the definition of recursion, although dynamic programming can use recursion from time to time. The main difference is that a recursive algorithm repeats the same procedure on the subproblem of same type of problem. Whereas a dynamic algorithm caches the results of each subproblem so that every subproblem is only solved once (1). Recursion can end up solving the same subproblem multiple time as it calls up the stack this for obvious reasons is inefficient, dynamic programming uses varying technics to avoid this.

Step 1

            The steps to creating a dynamic algorithm can vary but there are a few steps that will help you create a dynamic program. Firstly, Identify the sub problem; this is most like the most important step. Like with recursion you most think about the problem set from the bottom up, what is most you can reasonably and efficiently reduce the problem into sub problems (2). This is easy to mishandle I’d advise sketching out graphs and trees on paper, it can be easy to make mistakes even if you just write it out and then start coding, you must understand the problem thoroughly before being able to code the solution.

Step 2

            Secondly, find the reoccurring operations that you will be conducting on the sub problem. Whether the algorithm is recursive or not this step seems more difficult than it is,  provided that you have completed step 1 successfully (2). This is where drawing out the tree of executions come in handy it becomes clear what the base case is going to be and what the recursive case is going to be or steps of operation.

Step 3

            Thirdly, use the preceding steps to solve the entire problem this is a slightly harder step then it seems. As connecting the sub problem logic to solve the larger problem can seem daunting and edge cases can commonly slip through the cracks but if you have been diligent on these steps it should not be too difficult.

Step 4

            Lastly caching or memoization, this is the clear step where dynamic programming differs from recursive algorithms. Commonly called a memoization data structure commonly a hash or array. This array is used to store the results of expensive process in the algorithm, so if you are doing the same computation many times that uses results of previous computation that you are recomputing. Then you should set up your memoization array to save those  results. The difficult part is deciding the dimension and directions of how it should be filled out (2). This can be tricky the dimensions of the array rely on the number and size of the variable of the operation that is taking place in step 2. The direction will also just derive whether you are solving the problem bottom up or top down.

Dynamic programming as concept can be a little tricky to explain but makes sense once you start coding the algorithm. So, for next week I will walk through and algorithm and how to create a dynamic version of it. Thanks for reading!

Source:

  1. https://weibeld.net/algorithms/recursion.html#:~:text=Recursion%3A%20repeated%20application%20of%20the,subproblem%20is%20solved%20only%20once.
  2. https://www.freecodecamp.org/news/demystifying-dynamic-programming-3efafb8d4296/

Arrow Functions

            Arrow functions in JavaScript are another new feature released with ES6 with a lot of benefits to start using. Arrow functions are pretty commonplace now but might confuse some newer JavaScript developers, but they are much simpler and straight forward than they seem.  The main benefit of a using arrow function is it makes it much easier to write concise and clear functioning a much smaller amount of code and is especially useful when writing a one-line function as it also has implicit returns. In short coming across an arrow function can be confusing as it might look like some kind of strange way of declaring an object, but it just takes the function key word out of declaring a function. Here’s how you declare a simple arrow function.

let sum = (a, b) =>  a + b;

This function simply adds two numbers together, to declare the same function in the non-arrow traditional form you’d have to write it like this.

function sum(a, b) {
 return a + b;
}

As you can see even though this is an absurdly simple function the arrow function makes it much simpler and, in this case, much easier to understand. If you are not creating a one liner function you can obviously still make multi lined function with arrow functions. For instance if you are summing all the elements of an array.

Non-arrow way:

function sum(arr) {
	let sum = 0;
	arr.forEach (function (num) {
		sum += num
	});
	return sum;
}

Arrow function way:

const sum = (arr) => {
	let sum = 0
	arr.forEach ((num) => {
	
		sum += num	
	})
	return sum

}

As you can see arrow functions can also be used for iterators (the forEach) and other built in functions. Another slightly different syntax of a arrow function is the single argument function I am personally not a huge fan as it doesn’t save much space and doesn’t make the function any clearer but here is a quick example.

const half = a => a/2;

As you can see this function takes half of whatever number is inputted and the only real difference is not putting parenthesis around the variable.

The key differences between traditional function and arrow functions is how they use ‘this’. In a traditional function this is bound to the object that called the function. On the other hand, arrow function ‘this’ is always represents the object that defines the arrow function, in the example above it would be the const sum declaration of the function. This can cause some unintended consequences but if you’d like to use this in a more traditional way you will have to use the .bind() method. The different uses of this and how and how and why they are designer a certain way are a bit complicated and can be their own blog post, here is a good one (link) I found that goes into a lot more detail on how bind works in arrow functions. I hope this brief overview of arrow functions was helpful, happy coding!

Const and Let

ES6 or ESCMAScript 6 or the European Computer Manufacturer’s Association Script 6 if your really want to be the most verbose, is the newest standardized version of JavaScript as of this date. Although ES6 was released in June of 2015, still see many programmers not using ignoring some its useful features. =So, let us talk about a one of ES6’s most valuable feature const and let and when to use them (hint always use them over var).

Const and let, are two new ways ES6 allows us to declare variables, gone are the days of var and most experts agree to almost never use var again. Var was in my opinion a little too unspecific in its duties, especially as a developer who mostly used Java and C in his schooling. Var was the only way to declare a variable, it also had the ability for whatever reason to be redeclared at the same scope or deeper into that scope allowing you to hoist the new declared version of the var variable out of the deeper scope. As to why you would do this? I am not sure, maybe there is a scenario out there but seems like it could only cause problems. That’s where the two new ways of declaring variables come in.

Let

Let’s talk about let, which both of these declaration are pretty self-explanatory but I love the idea of let as it kind of infers  its meaning as “lets say this variable is i = 0” this variable similar to var can be mutated but cannot be redeclared inside its own scope here’s an example of the difference.

let msg = ‘hello world’
let msg = ‘what’s up world’
if(msg.length > 4) {
	let msg = ‘one level deeper into the scope’
console.log(msg)
} 
Console.log(msg)

This piece of code will throw the error:

error: unknown: Identifier 'msg' has already been declared.

But if we take out the second declaration but keep the third like this:

let msg = ‘hello world’
msg = ‘what’s up world’
if(msg.length > 4) {
	let msg = ‘one level deeper into the scope’
console.log(msg)
}
Console.log(msg)

Console:

“one level deeper into the scope”
“what’s up world”

Meaning if the variable can be “re-declared deeper in the scope” but you are actual just creating a new variable deeper in the scope that happens to have the same name which is not a great practice as you will not be able to use the one declared before that but you can still do this if you’d like. The important thing is that you cannot technically re-declare the variable which is very important to keep yourself sane as a programmer. Var on the other hand you can do whatever you want for example:

var msg = ‘hello world’
var msg = ‘why would you want to do this?’
console.log(msg)
if(msg.length > 4) {
	var msg = ‘why can you  do this it’s so dumb!’
} 
console.log(msg)

console:

“why would you want to do this?”
“why can you  do this it’s so dumb!”

As you can see for whatever reason you can basically do whatever you want with var regardless to how unsafe and unpractical.

Const

Now lets talk about const, const is even more straight forward than let simple put const stands for constant mean once you use const to declare something it cannot be declared again like let and it cannot be reassigned to a different value at that scope level. So, for example let:

const msg = ‘hello world’
if(msg.length > 4) {
	const msg = ‘one level deeper into the scope’
console.log(msg)
}
msg = ‘wait I want the message to be something else' 
console.log(msg)

console:

error: Uncaught TypeError: Assignment to constant variable.

This code through the error because you cannot change the value of a const but if we take that line out:

const msg = ‘hello world’
if(msg.length > 4) {
	const msg = ‘one level deeper into the scope’
console.log(msg)
}
console.log(msg)

console:

“one level deeper into the scope”
“hello world”

As you can see much like let it can be redeclared once your scope is a level deeper but will ”revert” back to its original value once out of that scope. Meaning the values if “redeclared” stay with the scope as a new variable but has nothing to do with the first variable in a sense.

So, overall stop using var it is never a good choice let is the right choice for any variable you are changing like a sum, temp, or count. Const is a great choice for well a constant variable a global, something like a URL that will not change. I hope this overview of const and let was helpful and helps you with future projects.

Functional vs Class Based React

If you use React you may have heard a growing consensus that using functional react for everything component is now “best practices” for React development. In my opinion best practices is a buzz phrase that people throw out there a lot that to seem like it means a whole lot but really means nothing at all. If you or someone else is writing a piece of code and their reason for writing it a certain way is “because it’s a best practice” that’s a horrible answer, to me the idea of best practices is just conscious of why your coding a certain way and if you think that way is the most efficient way to write it. Nothing should be as broad of a statement as “it’s a best practice now to do it this way” that’s taking all thinking of how to design your code out of the process and just doing it one because someone said so. Now that I have that tangent about “best practices” out of the way in regard to functional react let’s talk about the differences between functional and class component react.

Readability

Functional React a very obvious difference is syntax, functional React is just plain JavaScript which might be slightly easier to write and understand. I think the readability factor is a little overrated in this comparison, I have never thought that class component based React was particularly unreadable and I personally actually find some of the functional React’s advanced methods (life cycle methods compared to hooks and so on) a little less readable than there class based counter parts but maybe that’s just because a lot of them are a little newer and I am not used to them yet. Overall functional React has much cleaner look especially for basic components, with no render function, or life cycle and state functions, although hooks have changed that a little.

Efficiency

 Functional React runs away with this one, without having to use the render function like class based React, and class based React can have a lot of redundant renders. This is not to say that class Based React can’t be efficient you just have to be conscious of what might cause a re-render and if that was necessary re-render. Using life cycle methods like shouldComponentUpdate with componentWillUpdate or React pure component can be helpful. Functional components are much more lightweight and just take a lot less overhead compared to all the features and overhead of class based React.

When to Use One or the Other

With hooks it seems like you can basically do whatever class-based components can do but quicker and more readable. Well this might be true for many aspects there are still many uses for class-based components, and it doesn’t seem like the React team is going to phase out class-based components anytime soon. For example advanced features such as hooks for functional components can have varying of less than perfect side affects like useEffect basically the functional version of ComponentDidMount (but definitely different a few important ways) especially when using async/await as effect callback function cannot be async. There are many small examples like these and overall if you have a complex component it might be best to write it as class-component or to not port it over to a functional component because it is “best practices”. There will always be new features being added and this amateur React developer’s blog will more than likely be obsolete, so it is always best to do your own research and figure out what mix of components for your project will work best.

Sources:

  1. https://medium.com/@Zwenza/functional-vs-class-components-in-react-231e3fbd7108#:~:text=But%20there%20are%20some%20benefits,you%20to%20use%20best%20practices.
  2. https://reacttraining.com/blog/useEffect-is-not-the-new-componentDidMount/#:~:text=They’re%20almost%20the%20same,network%20call%20or%20a%20subscription.
  3. https://blog.bitsrc.io/improve-performance-in-react-functional-components-using-react-memo-b2e80c11e15a
  4. https://blog.bitsrc.io/will-react-classes-get-deprecated-because-of-hooks-bb62938ac1f5
  5. https://medium.com/@stojanpeshov/react-hooks-component-will-mount-2c21ba2778a1#:~:text=You%20can%20only%20use%20Hooks,in%20a%20class%20components.

Web Scrapping

Web scrapping simple put is just a way to programmable get data from a website. Every business, product, and even your small personal side projects need data. Data drives everything and there are many great databases with user friendly APIs but sometimes when you need very large amounts of data or when there is no existing database, you will have to use a web scrapper to fill your database, as someone likely did before you till fill the databases you already use. Web scrapping allows to make a perfectly customizable API for whatever project you are working on, if you just want an email alert every time a job comes up all these app are made easy with web scrapping the time you take now to automate something will save a lot of time in the future.

Basic web scrapping is a lot easier than you think, like previously stated data is always needed and therefore web scrapping is extremely popular and with popularity comes a lot of tools that make it easier to web scrape. The first and foremost step of web scrapping is to find the data you need, search for particular site with whatever data you are looking for. Be careful though web scrapping can become a headache fast if a site is unorganized and HTML elements are reused in illogical ways that can render your web scrapper useless, especially if you are using a web crawler, just moving between a lot of pages on the site; if you are just pull data from one page as it updates on the site then as long as the web page isn’t horrifically designed you should be okay. With that being said things to look for in a site are consistent pages that you can pull the data from a few selected HTML elements across multiple pages with having to go through manually each time. If you are trying to pull articles from a website but the HTML elements are used all over the place and requires you to check the data each time so you don’t accidently pull the comment section, then you might want to look elsewhere.  Make sure that the routing of the site is logical, you want to make sure that the routing around the site is logical, if you click on someone’s an article on the site and the address bar says something like http://www.news.com/articles/headline but when you click on another article and the address bar says something like http://www.news.com/posts-articles23/headline. Then you might have a problem if there is no discernable logic beside poor programming then this is most likely a site that is not worth the extra time and effort to scrape from.  Overall these are just a few tips before you start scrapping that you will pick up on pretty fast. Just use your inspect tool in your DevTools and do some poking around and you should be able to figure out pretty fast if the site is a good fit for you. I hope this was helpful I’ll link a list some scarping tools down below for you to decide which one is best.

Web Scrapping Tools

Sources

  1. https://towardsdatascience.com/https-medium-com-hiren787-patel-web-scraping-applications-a6f370d316f4

JavaScript Frontend Frameworks/Libraries

            The proliferation of JavaScript frameworks seems to be never ending at this point and which one to use can be hard to decide with some capabilities and levels of support, most the popular ones come down to preference. First let’s talk about why there are so many JS frameworks, JS was originally just a browser based language that was used to support events and other things of that nature but since it was not standardizes properly it was inconsistent across browsers making it difficult to use. Meaning that for any rich interactivity you had to use something like Flash, which we can all agree was not the greatest solution. Once JS was standardized, frameworks began to pop up everywhere with notable ones being Node.js allowing cross-platform capabilities making JavaScript more than a browser-based language and then jQuery. For a while jQuery was the clear framework to use as it had beat out all its competitors for the top spot but as preference and design changed so did the frameworks (1). New ones popping up all the time, we are now in a period where it is not one framework vying for the top spot but many frameworks that are most likely interchangeable in and it comes down to specific ease of use for one project to another and you can easily switch frameworks if needed down the road. Now let us talk about a couple popular frontend frameworks and the advantages and the disadvantages between them. Huge disclaimer I am not an expert and only have experience in React.js but have sourced information from others also might use frameworks and libraries interchangeably I know they are different but not the purpose of this post.

Angular/AngularJS

            Both created by a team at google, Angular is just the newer typescript version of AngularJS, they are both popular and used commonly. Angular allows developers to write apps in a strict MVC in a simpler way using components then binding them to ngRouter and ngHttp, it is also a very secure framework that uses dependency injection to help protect your code (2). Although it is a little harder to learn than most frameworks, it is highly opinionated meaning there is usually only one way to do something this allows for cleaner code, and there for more readability between developers. Although angular has become much more modular in recent years, it gives you all your tools out of the box which is nice but can result in longer compile times (3).

React

            React created by Facebook, which is a very popular library.  It is an extraordinarily lightweight framework which make it a little easier to get started but not as easy as some. For advance functionality you will have to get additional packages. React allows you to design your web application in a lot of different ways compared to something like Angular which allows it to be easier to use but can affect readability at times and can affect security. React uses components that are rendered to a virtual DOM tree (3).

Vue

          Vue also created by google is kind of the in between of popularity and is overall considered the easiest to learn most likely in part because it is the most lightweight framework, for basic functionality you’ll need some packages but it compiles fast and is easy to get started. Vue keeps the logis and the markup separated well which allows for better readability and understanding. The lack in power might be noticeable in some advanced features but for personal projects and so on it might be the ideal place to start (3).

I hope this brief intro into JS frameworks helped and helps you choose a framework in the future.

Sources:

  1. https://www.evolutionjobs.com/uk/media/why-are-there-so-many-javascript-frameworks-188799/
  2. https://huspi.com/blog-open/what-javascript-framework-to-choose-in-2020-a-comparison
  3. https://teamtreehouse.com/community/pros-cons-of-3-popular-javascript-frameworks

CRISPR

The current innovations being made in genetic engineering are possibly some of the most fascinating, and life changing in any scientific field today. I will be going over just a few of them in this post but there are many more out there; the first innovation that is Clustered Regularly Interspaced Short Palindromic Repeats or CRISPR.

            I will be talking about more specifically CRISPR-Cas9, while in modern genetic engineering researchers have made many strive most importantly mapping the entire human genome. The major obstacle scientists ran into was no having an efficient way to edit genes, and that’s where CRISPR has become revolutionary. CRISPR-Cas9 as we know it today was created by Jennifer Doudna and Emmanuelle Charpentier who simplified the process by fusing together two molecules of RNA into one. CRISPR’s roots can however be traced all the way back to the late 1980s when Yoshikizumi Ishino discovered cluster DNA repeats when he accidentally cloned part of a CRISPR together with the target gene (NCBI).

 CRISPR uses a human made molecule that contains the Cas9 nucleus protein, to which the programmable guide RNA is then set to the desired gene to be edited. CRISPR basically repurposed a process scientists had known for a while, in which your immune systems find certain gene from virus to eradicate them, researchers using the aforementioned tool used this process to easily manipulate specific genes. This technology allows a much-needed ease of use and affordability to the gene editing processes.  With CRISPR scientists can now edit genes with accuracy, speed, and precision that they never could before. Now genes can be edited, deleted, and mutated in a relatively short time, and in a much more affective way. Before CRISPR any changes to a genome would have to be tailor made to the section of DNA the specific kind of cells and the organism, all of which would take years and millions of dollars. With CRISPR sparing a few details all that needs to be changed is the guide RNA, then it can be used as desired. Because of this comparable noncomplex nature of CRISPR, it can have many different applications; such as gene editing simply put the copy and/or pasting of genes, RNA editing, and knockdown or activations the activations or suppression a particular gene.

Even with all of these applications CRISPR is still a fairly new technology and has much more research to be done. The inventors of CRISPR have urged researcher around the world to avoid using CRISPR in human clinical trials due to the need for further analysis. As recently as April of 2015 Chinese scientist attempted to modify the DNA of a non-viable human embryo in an attempt to amend a segment that attributed to specific genetic blood disorder belonging under the group of disorders known as Thalassemia a subgroup of anemia disorders. The result this experiment proved the aforementioned warnings, as the trial only produced changes to some of the genes and had off-target effects on others (Nature).  Although as of now the technologies like CRISPR are not ready for medical trials, it is not too soon to be speculating on the future impacts this and other technologies surrounding genetic engineering will have on humanity; next week I will be covering these future possibilities.

NCBI

https://www.ncbi.nlm.nih.gov/pmc/articles/PMC213968/

Nature

http://www.nature.com/news/chinese-scientists-genetically-modify-human-embryos-1.17378

Learning to Code

            As many of us know to begin your journey as a coder can be daunting, with taking your first computer science class or “self-teaching” using online tutorials all the syntax and nomenclature can be extremely confusing and can turn a lot of young people off the path of knowing how to code but it doesn’t have to be this way. At its core programming is just simple puzzle solving, you’re directing chain events to build something useful or enjoyable. This is why the language Snap! Was developed, it’s a block-based free educational coding languages which allows students to create all kinds of fun projects and games while simultaneously learning the basics of how to code.  

Snap!, from the get go was designed with student learning in mind with it formerly having been called the more descriptive name BYOB or Build Your Own Blocks. The core of the language is written JavaScript but the major idea being the ability to take all syntax out the programming language and allow students to drag and drop different pieces of coding logic to create their graphical applications. When confronted with the issue of Snap being considered a “baby programming language” the creator of Snap Brian Harvey stated

“It’s a very serious programming language, in disguise. The reason for the disguise is that most programming courses spend most of their time and effort on the details of the notation used by whatever programming language they choose. Here’s the classic example: In your “grownup” programming language you

write some stuff; some more stuff; and yet more stuff;”.

Snap takes complex programming ideas and makes them as accessible as possible, while still having the power of a language like JavaScript to have advanced functionality. Brian goes on to say

“These are three instructions to the computer, with semicolons in between. Now, what about that red semicolon at the end? If the language is Java, C, or C++, that semicolon is required. If it’s Perl, Pascal, or PL/I, that semicolon is forbidden. Not exactly easy to learn. But if, instead, the code looks like this:

then there’s no need to remember punctuation rules. The visual layout of the code is the notation.”

This allows Snap! a lot of flexibility as it can be used to introduce middle schoolers to code, as well as being in a Ivy League University’s curriculum, it can do most anything that a lot of other programming languages can do on their base level without using all kinds of libraries. Snap has simplicity of Legos but the key difference that allows you to do more with snap is you can build your own blocks which is where the complex programming can come into play allowing you to creating almost any of the same interactions of vanilla JavaScript. Although most people will start to learn programming using language like python, ruby and java; if you know anyone who is thinking of learning how to code make sure they consider snap because in the long wrong getting the thinking patterns and problem solving abilities quicker will save them time than trying to learn the syntax of an in demand coding language.

Sources:

Algorithm Time Complexity Analysis

Knowing approximately how long your algorithm will take is key to writing efficient and dynamic code. Time complexity of your algorithm can be very important to your code the especially the larger the dataset that you are working with. It is important as a developer to have a system of to analyze your code, to make it most efficient regardless of what machine it is running on. This is where asymptotic analysis comes in; asymptotic analysis is a algorithm time complexity analysis that doesn’t depend on any machine specific constants. This process uses three types of notations:  θ (theta), O (big O), and Ω (Omega) (1) along with these notations all use the letter ‘n’ to denote the time complexity meaning it takes ‘n’ number tasks to complete this algorithm, meaning each task takes the same amount of time. All of which have different exact uses but all essentially work the same; we will first briefly go over each one then go over some time complexity examples using big O notation as it is the most commonly used notation.

Omega notation bounds the algorithm by its lower bound and is known as the getting the  best possible time complexity your algorithm can run at. This can be useful to know, especially just to find out what is the most optimal data set to use an algorithm for. Theta notation bounds the time complexity of an algorithm from below and above giving a kind of “average” time complexity. Given the structure of the algorithm theta can be useful to use to know how long your algorithm will most likely take on a non-edge case data set. Lastly, Big O which is the most used algorithm for obvious reasons as it is the upper bound of the time complexity of a particular algorithm. It is always important to know the worst-case scenario, if you have and algorithm that runs extremely fast in most cases but will take 100 times longer in one case that can be a huge problem.

First let get the time complexity of a simple loop.

for(int i = 0; i < 5; i++) {
	System.out.println(“Hello”);
}

This loop will run 5 times from i=0 to i=5 so it will have a constant time complexity, as it runs two-line this means the total time t(n) = 2*(5) = 10 but the asymptotic analysis doesn’t care about the exact time it only cares that it is constant so it denotes it as O(1) meaning it will always take the same amount of time no matter what. Now let’s check out another variable loop.

for(int i = 0; i < n; i++) {
	System.out.println(“Hello”);
}

This loop you no longer know  exactly how long it is going to take, but it is dependent on how big of a value ‘n’ is. So, the time complexity is t(n) = 2*n. Again, we do not care about the constants so the Big O is O(n) as it will roughly take n times to run this loop.

Thanks for reading my brief overview of time complexity I hope it’s a good launching off point for more in-depth time complexity analysis. Here is also a quick algorithm time complexity cheat sheet.

Sources:

  1. https://www.geeksforgeeks.org/analysis-of-algorithms-set-3asymptotic-notations/
Design a site like this with WordPress.com
Get started