How data-savvy are you, really? Take our quiz to find out.

Which program is right for you?

MIT Sloan Campus life

Through intellectual rigor and experiential learning, this full-time, two-year MBA program develops leaders who make a difference in the world.

A rigorous, hands-on program that prepares adaptive problem solvers for premier finance careers.

A 12-month program focused on applying the tools of modern data science, optimization and machine learning to solve real-world business problems.

Earn your MBA and SM in engineering with this transformative two-year program.

Combine an international MBA with a deep dive into management science. A special opportunity for partner and affiliate schools only.

A doctoral program that produces outstanding scholars who are leading in their fields of research.

Bring a business perspective to your technical and quantitative expertise with a bachelor’s degree in management, business analytics, or finance.

A joint program for mid-career professionals that integrates engineering and systems thinking. Earn your master’s degree in engineering and management.

An interdisciplinary program that combines engineering, management, and design, leading to a master’s degree in engineering and management.

Executive Programs

A full-time MBA program for mid-career leaders eager to dedicate one year of discovery for a lifetime of impact.

This 20-month MBA program equips experienced executives to enhance their impact on their organizations and the world.

Non-degree programs for senior executives and high-potential managers.

A non-degree, customizable program for mid-career professionals.

Harvard Square: A Love Story

How companies use AI to reach customers, innovate

Creating change through collaborative participation

Credit: Alejandro Giraldo

Ideas Made to Matter

How to use algorithms to solve everyday problems

Kara Baskin

May 8, 2017

How can I navigate the grocery store quickly? Why doesn’t anyone like my Facebook status? How can I alphabetize my bookshelves in a hurry? Apple data visualizer and MIT System Design and Management graduate Ali Almossawi solves these common dilemmas and more in his new book, “ Bad Choices: How Algorithms Can Help You Think Smarter and Live Happier ,” a quirky, illustrated guide to algorithmic thinking. 

For the uninitiated: What is an algorithm? And how can algorithms help us to think smarter?

An algorithm is a process with unambiguous steps that has a beginning and an end, and does something useful.

Algorithmic thinking is taking a step back and asking, “If it’s the case that algorithms are so useful in computing to achieve predictability, might they also be useful in everyday life, when it comes to, say, deciding between alternative ways of solving a problem or completing a task?” In all cases, we optimize for efficiency: We care about time or space.

Note the mention of “deciding between.” Computer scientists do that all the time, and I was convinced that the tools they use to evaluate competing algorithms would be of interest to a broad audience.

Why did you write this book, and who can benefit from it?

All the books I came across that tried to introduce computer science involved coding. My approach to making algorithms compelling was focusing on comparisons. I take algorithms and put them in a scene from everyday life, such as matching socks from a pile, putting books on a shelf, remembering things, driving from one point to another, or cutting an onion. These activities can be mapped to one or more fundamental algorithms, which form the basis for the field of computing and have far-reaching applications and uses.

I wrote the book with two audiences in mind. One, anyone, be it a learner or an educator, who is interested in computer science and wants an engaging and lighthearted, but not a dumbed-down, introduction to the field. Two, anyone who is already familiar with the field and wants to experience a way of explaining some of the fundamental concepts in computer science differently than how they’re taught.

I’m going to the grocery store and only have 15 minutes. What do I do?

Do you know what the grocery store looks like ahead of time? If you know what it looks like, it determines your list. How do you prioritize things on your list? Order the items in a way that allows you to avoid walking down the same aisles twice.

For me, the intriguing thing is that the grocery store is a scene from everyday life that I can use as a launch pad to talk about various related topics, like priority queues and graphs and hashing. For instance, what is the most efficient way for a machine to store a prioritized list, and what happens when the equivalent of you scratching an item from a list happens in the machine’s list? How is a store analogous to a graph (an abstraction in computer science and mathematics that defines how things are connected), and how is navigating the aisles in a store analogous to traversing a graph?

Nobody follows me on Instagram. How do I get more followers?

The concept of links and networks, which I cover in Chapter 6, is relevant here. It’s much easier to get to people whom you might be interested in and who might be interested in you if you can start within the ball of links that connects those people, rather than starting at a random spot.

You mention Instagram: There, the hashtag is one way to enter that ball of links. Tag your photos, engage with users who tag their photos with the same hashtags, and you should be on your way to stardom.

What are the secret ingredients of a successful Facebook post?

I’ve posted things on social media that have died a sad death and then posted the same thing at a later date that somehow did great. Again, if we think of it in terms that are relevant to algorithms, we’d say that the challenge with making something go viral is really getting that first spark. And to get that first spark, a person who is connected to the largest number of people who are likely to engage with that post, needs to share it.

With [my first book], “Bad Arguments,” I spent a month pouring close to $5,000 into advertising for that project with moderate results. And then one science journalist with a large audience wrote about it, and the project took off and hasn’t stopped since.

What problems do you wish you could solve via algorithm but can’t?

When we care about efficiency, thinking in terms of algorithms is useful. There are cases when that’s not the quality we want to optimize for — for instance, learning or love. I walk for several miles every day, all throughout the city, as I find it relaxing. I’ve never asked myself, “What’s the most efficient way I can traverse the streets of San Francisco?” It’s not relevant to my objective.

Algorithms are a great way of thinking about efficiency, but the question has to be, “What approach can you optimize for that objective?” That’s what worries me about self-help: Books give you a silver bullet for doing everything “right” but leave out all the nuances that make us different. What works for you might not work for me.

Which companies use algorithms well?

When you read that the overwhelming majority of the shows that users of, say, Netflix, watch are due to Netflix’s recommendation engine, you know they’re doing something right.

Related Articles

An illustration of a business person climbing a wall of data

If you're seeing this message, it means we're having trouble loading external resources on our website.

If you're behind a web filter, please make sure that the domains *.kastatic.org and *.kasandbox.org are unblocked.

To log in and use all the features of Khan Academy, please enable JavaScript in your browser.

AP®︎/College Computer Science Principles

Unit 4: lesson 3, using heuristics.

Traveling Salesperson Problem

The brute force approach, developing a heuristic, the nearest-neighbor heuristic, heuristics everywhere, want to join the conversation.

Good Answer

Related Articles

What is Algorithm | Introduction to Algorithms

What is an Algorithm? Algorithm Basics

The word Algorithm means ” A set of finite rules or instructions to be followed in calculations or other problem-solving operations ” Or ” A procedure for solving a mathematical problem in a finite number of steps that frequently involves recursive operations” .

Therefore Algorithm refers to a sequence of finite steps to solve a particular problem.

Use of the Algorithms:-

Algorithms play a crucial role in various fields and have many applications. Some of the key areas where algorithms are used include:

Computer Science: Algorithms form the basis of computer programming and are used to solve problems ranging from simple sorting and searching to complex tasks such as artificial intelligence and machine learning.

Mathematics: Algorithms are used to solve mathematical problems, such as finding the optimal solution to a system of linear equations or finding the shortest path in a graph.

Operations Research : Algorithms are used to optimize and make decisions in fields such as transportation, logistics, and resource allocation.

Artificial Intelligence: Algorithms are the foundation of artificial intelligence and machine learning, and are used to develop intelligent systems that can perform tasks such as image recognition, natural language processing, and decision-making.

Data Science: Algorithms are used to analyze, process, and extract insights from large amounts of data in fields such as marketing, finance, and healthcare.

These are just a few examples of the many applications of algorithms. The use of algorithms is continually expanding as new technologies and fields emerge, making it a vital component of modern society.

Algorithms can be simple and complex depending on what you want to achieve.

It can be understood by taking the example of cooking a new recipe. To cook a new recipe, one reads the instructions and steps and executes them one by one, in the given sequence. The result thus obtained is the new dish is cooked perfectly. Every time you use your phone, computer, laptop, or calculator you are using Algorithms. Similarly, algorithms help to do a task in programming to get the expected output.

The Algorithm designed are language-independent, i.e. they are just plain instructions that can be implemented in any language, and yet the output will be the same, as expected.

What is the need for algorithms:

1.Algorithms are necessary for solving complex problems efficiently and effectively. 

2.They help to automate processes and make them more reliable, faster, and easier to perform.

3.Algorithms also enable computers to perform tasks that would be difficult or impossible for humans to do manually.

4.They are used in various fields such as mathematics, computer science, engineering, finance, and many others to optimize processes, analyze data, make predictions, and provide solutions to problems.

What are the Characteristics of an Algorithm?

As one would not follow any written instructions to cook the recipe, but only the standard one. Similarly, not all written instructions for programming is an algorithms. In order for some instructions to be an algorithm, it must have the following characteristics:

Properties of Algorithm:

Types of Algorithms:

There are several types of algorithms available. Some important algorithms are:

1. Brute Force Algorithm : It is the simplest approach for a problem. A brute force algorithm is the first approach that comes to finding when we see a problem.

2. Recursive Algorithm : A recursive algorithm is based on recursion . In this case, a problem is broken into several sub-parts and called the same function again and again.

3. Backtracking Algorithm : The backtracking algorithm basically builds the solution by searching among all possible solutions. Using this algorithm, we keep on building the solution following criteria. Whenever a solution fails we trace back to the failure point and build on the next solution and continue this process till we find the solution or all possible solutions are looked after.

4. Searching Algorithm : Searching algorithms are the ones that are used for searching elements or groups of elements from a particular data structure. They can be of different types based on their approach or the data structure in which the element should be found.

5. Sorting Algorithm : Sorting is arranging a group of data in a particular manner according to the requirement. The algorithms which help in performing this function are called sorting algorithms. Generally sorting algorithms are used to sort groups of data in an increasing or decreasing manner.

6. Hashing Algorithm : Hashing algorithms work similarly to the searching algorithm. But they contain an index with a key ID. In hashing, a key is assigned to specific data.

7. Divide and Conquer Algorithm : This algorithm breaks a problem into sub-problems, solves a single sub-problem and merges the solutions together to get the final solution. It consists of the following three steps:

8. Greedy Algorithm : In this type of algorithm the solution is built part by part. The solution of the next part is built based on the immediate benefit of the next part. The one solution giving the most benefit will be chosen as the solution for the next part.

9. Dynamic Programming Algorithm : This algorithm uses the concept of using the already found solution to avoid repetitive calculation of the same part of the problem. It divides the problem into smaller overlapping subproblems and solves them.

10. Randomized Algorithm : In the randomized algorithm we use a random number so it gives immediate benefit. The random number helps in deciding the expected outcome.

To learn more about the types of algorithms refer to the article about “ Types of Algorithms “.

Advantages of Algorithms:

Disadvantages of Algorithms:

How to Design an Algorithm?

In order to write an algorithm, the following things are needed as a pre-requisite:   

Then the algorithm is written with the help of the above parameters such that it solves the problem. Example: Consider the example to add three numbers and print the sum.  

Here is the step-by-step algorithm of the code:

Time complexity: O(1) Auxiliary Space: O(1) 

One problem, many solutions: The solution to an algorithm can be or cannot be more than one. It means that while implementing the algorithm, there can be more than one method to implement it. For example, in the above problem to add 3 numbers, the sum can be calculated in many ways like:

How to analyze an Algorithm? 

For a standard algorithm to be good, it must be efficient. Hence the efficiency of an algorithm must be checked and maintained. It can be in two stages:

What is Algorithm complexity and how to find it?

An algorithm is defined as complex based on the amount of Space and Time it consumes. Hence the Complexity of an algorithm refers to the measure of the Time that it will need to execute and get the expected output, and the Space it will need to store all the data (input, temporary data and output). Hence these two factors define the efficiency of an algorithm.  The two factors of Algorithm Complexity are:

Therefore the complexity of an algorithm can be divided into two types :

1. Space Complexity : The space complexity of an algorithm refers to the amount of memory required by the algorithm to store the variables and get the result. This can be for inputs, temporary operations, or outputs. 

How to calculate Space Complexity? The space complexity of an algorithm is calculated by determining the following 2 components:   

Example: Consider the below algorithm for Linear Search

Step 1: START Step 2: Get n elements of the array in arr and the number to be searched in x Step 3: Start from the leftmost element of arr[] and one by one compare x with each element of arr[] Step 4: If x matches with an element, Print True. Step 5: If x doesn’t match with any of the elements, Print False. Step 6: END Here, There are 2 variables arr[], and x, where the arr[] is the variable part of n elements and x is the fixed part. Hence S(P) = 1+n. So, the space complexity depends on n(number of elements). Now, space depends on data types of given variables and constant types and it will be multiplied accordingly.

2. Time Complexity : The time complexity of an algorithm refers to the amount of time that is required by the algorithm to execute and get the result. This can be for normal operations, conditional if-else statements, loop statements, etc.

How to calculate Time Complexity? The time complexity of an algorithm is also calculated by determining the following 2 components: 

Example: In the algorithm of Linear Search above, the time complexity is calculated as follows:

Step 1: –Constant Time Step 2: — Variable Time (Taking n inputs) Step 3: –Variable Time (Till the length of the Array (n) or the index of the found element) Step 4: –Constant Time Step 5: –Constant Time Step 6: –Constant Time Hence, T(P) = 5 + n, which can be said as T(n).

How to express an Algorithm?

Solve DSA problems on GfG Practice.

Please Login to comment...

In JAVA/C++ Language

Improve your Coding Skills with Practice

Start your coding journey now.

How to Think Algorithmically

Last Updated: December 16, 2021 References

This article was co-authored by wikiHow Staff . Our trained team of editors and researchers validate articles for accuracy and comprehensiveness. wikiHow's Content Management Team carefully monitors the work from our editorial staff to ensure that each article is backed by trusted research and meets our high quality standards. This article has been viewed 26,300 times. Learn more...

Although you might think only computers use algorithms, humans solve problems algorithmically every day. Read on to learn how to improve your own algorithmic thinking with new approaches to problem solving, and how you can practice these tools in everyday life.

Working out Problems Logically

Image titled Think Algorithmically Step 1

Image titled Think Algorithmically Step 2

Image titled Think Algorithmically Step 3

Image titled Think Algorithmically Step 4

Image titled Think Algorithmically Step 5

Image titled Think Algorithmically Step 6

Image titled Think Algorithmically Step 7

Image titled Think Algorithmically Step 8

Practicing in Your Everyday Life

Image titled Think Algorithmically Step 9

Image titled Think Algorithmically Step 10

Image titled Think Algorithmically Step 11

Image titled Think Algorithmically Step 12

Expert Q&A

You might also like.

Recognize and Avoid Brainwashing

About This Article

wikiHow Staff

Did this article help you?

Am I a Narcissist or an Empath Quiz

Featured Articles

Play FIFA 23 Career Mode

Trending Articles

Talk to a Girl in a Group

Watch Articles

Make Homemade Soup

Get all the best how-tos!

Sign up for wikiHow's weekly email newsletter

Solve Me First Easy Problem Solving (Basic) Max Score: 1 Success Rate: 98.17%

Simple array sum easy problem solving (basic) max score: 10 success rate: 94.35%, compare the triplets easy problem solving (basic) max score: 10 success rate: 95.60%, a very big sum easy problem solving (basic) max score: 10 success rate: 98.80%, diagonal difference easy problem solving (basic) max score: 10 success rate: 95.92%, plus minus easy problem solving (basic) max score: 10 success rate: 98.38%, staircase easy problem solving (basic) max score: 10 success rate: 98.36%, mini-max sum easy problem solving (basic) max score: 10 success rate: 94.34%, birthday cake candles easy problem solving (basic) max score: 10 success rate: 97.04%, time conversion easy problem solving (basic) max score: 15 success rate: 92.03%.

How to Solve Tough Problems Using Genetic Algorithms

how to solve problems using algorithms

What’s the connection between evolutionary algorithms and mother nature, and how can it help solve complicated computing problems?

Wikipedia defines evolution as “a change in the heritable characteristics of biological populations over successive generations”. While it often relates to mother nature, animals or humans, it’s also a part of the computing world. In the following post we’ll explore evolution through genetic algorithms, and see how it can help us solve problems faster.

Natural Selection in Code

Genetic algorithms imitate the evolution process in nature by evolving superior solutions to problems. Natural selection plays a major part in this process – the differential survival and reproduction of individuals due to differences in phenotype . According to Charles Darwin, also known as the “father” of evolutionary thought, natural selection is the key force that helps preserve good changes, and eradicate bad ones. This helps populations improve over time. Genetic algorithms mimic the power of evolution with code, along with natural selection, in order to solve problems better and faster. In computing, our population consists of a collection of solutions to a specific problem. Once we have the population, we can move on to the evolution process, which consists of the following steps: 1. Fitness – Giving a score to each solution, that represent how good it is 2. Selection – Selecting pairs of parent solutions according to their Fitness value 3. Crossover – Breeding the selected parents to produce an offspring 4. Mutation – Mutating the offspring solution with a very low probability The evolution process here leads to finding a “superior” solution to the problem, or at least so we hope.

The Evolution of the Traveling Salesman Problem

When choosing to use genetic algorithms (that’s part of evolutionary algorithms), the first thing we need to understand is how to represent an individual solution in our population. In order to understand how to do that, we’ll use the Traveling Salesman Problem (TSP):

Given a list of cities and the distances between each pair of cities, what is the shortest possible route that visits each city exactly once?

Or in other words, the Uber line or Lyft pool problem 😉

The Traveling Salesman Problem

The Traveling Salesman Problem

A solution to the problem can be represented as an ordered list of cities, when each one describes the desired route. And it’s important to point out that every city should be listed exactly once. In this example, our solution population consists of a collection of lists of cities. To form our first generation, we will randomly generate a collection of solutions, and we need to make sure that each generated solution is valid (and is a possible solution to the problem). We call these solutions chromosomes . The next step will be taking these chromosomes into a process of evolution, and use the power of natural selection to obtain a better population. In order to achieve this, we first need to evaluate each chromosome and give the better ones higher probabilities to produce children. This is done by a function called the Fitness Function that receives a chromosome, and returns a score that represents how good the chromosome is in terms of the problem. Going back to our example, the function could be the sum of the distances in the route. At this point we take the scores, and each chromosome will get a relative probability to be selected as parent for the next generation. And as we mentioned earlier, better chromosomes will get higher probabilities. Or in other words, this is where we use natural selection and now it’s time to move to the process of evolution.

Creating a Better Solution, Each Time

Our main goal is to select “parents” based on their probabilities (calculated by their fitness score), breed them, and move the produced child into the next generation. The breeding process is derivative of the problem, when we need to find a way to combine the parents into a valid solution. When trying to breed parents, the first idea that comes up is to take 50% from each one. However, in the Travelling Salesman Problem (TSP) it might lead to an invalid solution – in which each city will appear more than once. So how can we solve this? By taking the first part from the first parent, and then taking the rest of the cities according to their order of appearance on the second parent solution. We can be as creative as we want, as long as we make sure that we’re generating a valid solution that combines both parents. Before we can take the child we created into the “next generation”, we need to apply mutation with a very low probability. How can we do this? Well, it depends on the problem we’re facing and just like before, we need to make sure that the mutated chromosome is still a valid solution. In our TSP example, this means that we can draw two cities and switch them – the mutated route is valid since each city appears once.

Circle of Life

When and why should we use genetic algorithms.

Now that we know how genetic algorithms work, it’s time to wonder when we should actually use them. The top use case is for optimization problems, when we’re facing a big search space, where other search algorithms have failed. But, why would we think that genetic algorithms would perform better? When thinking about it, we just start with a random collection of solutions hoping to eventually find a good one. It almost feels like we’re counting on sheer luck for our process to work. How do we make it work? By using: 1. Mutation – that encourages diversity which spreads the chromosomes over the search space, helping us discover as many hills as possible 2. Selection and Crossover – that encourages homogeneity by mating the top performing chromosomes with higher probabilities. Selection and Crossover will help us “climb up the hills”, and all three elements combined will handle the high number of solutions we’ll get. We know how and when to use genetic algorithms, the only thing left is to understand if we can use it for the problem we’re facing. There are 2 prerequisites that makes our problem eligible for using genetic algorithms: 1. We need to understand how to represent a solution to the problem 2. We should have the ability to calculate continuous fitness If our problem meets these criteria, we’re good to go. There are some nice examples of problems genetic algorithms helped solve, but our favorite one is the evolving Mona Lisa , in which the algorithm creates an approximation of the Mona Lisa using 250 semi transparent circles. If you want to get started with genetic algorithms, there are plenty of libraries out there you can try. The 2 most common libraries you should check out are Jenetics and JGAP .

Final Thoughts

Tzofia Shiftan

During her time at OverOps . Tzofia served as Head of Application Development. She is the founder of the R&D Leaders Group in Tel Aviv, and in her spare time, she likes to collect doodads from all over the world.

how to solve problems using algorithms

Troubleshooting Apache Spark Applications with OverOps

We'll email you the latest blog posts

Next Article

how to solve problems using algorithms

Infographic: The Weirdest Things Written to Log Files - Based on 3,648,131 Words

The fastest way to why., eliminate the detective work of searching logs for the cause of critical issues. resolve issues in minutes..

OverOps

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.

Strictly Necessary Cookie should be enabled at all times so that we can save your preferences for cookie settings.

If you disable this cookie, we will not be able to save your preferences. This means that every time you visit this website you will need to enable or disable cookies again.

The Algorithm Problem Solving Approach in Psychology

Kendra Cherry, MS, is an author and educational consultant focused on helping students learn about psychology.

how to solve problems using algorithms

 James Lacy, MLS, is a fact-checker and researcher.

how to solve problems using algorithms

Examples of Algorithms

Algorithms vs. Heuristics

When solving a problem , choosing the right approach is often the key to arriving at the best solution. In psychology, one of these problem-solving approaches is known as an algorithm. While often thought of purely as a mathematical term, the same type of process can be followed in psychology to find the correct answer when solving a problem or making a decision.

What Is an Algorithm in Psychology?

An algorithm is a defined set of step-by-step procedures that provides the correct answer to a particular problem. By following the instructions correctly, you are guaranteed to arrive at the right answer.

An algorithm is often expressed in the form of a graph, where a square represents each step. Arrows then branch off from each step to point to possible directions that you may take to solve the problem. In some cases, you must follow a particular set of steps to solve the problem. In other instances, you might be able to follow different paths that will all lead to the same solution.

This article discusses how algorithms are used as an approach to problem-solving. It also covers how psychologists compare this approach to other ways to solve problems.

There are many different examples of how algorithms can be used in daily life. Some common ones include:

Reasons to Use Algorithms in Psychology

The upside of using an algorithm to solve a problem or make a decision is that yields the best possible answer every time. There are situations where using an algorithm can be the best approach:

Potential Pitfalls When Using Algorithms

The downside of using an algorithm to solve the problem is that this process tends to be very time-consuming. So if you face a situation where a decision needs to be made very quickly, you might be better off using a different problem-solving strategy.

For example, an emergency room doctor making a decision about how to treat a patient could use an algorithm approach. However, this would be very time-consuming and treatment needs to be implemented quickly. In this instance, the doctor would instead rely on their expertise and past experiences to very quickly choose what they feel is the right treatment approach.

Algorithms can be a great problem-solving choice when the answer needs to be 100% accurate or when each decision needs to follow the same process. A different approach might be needed if speed is the primary concern.

In psychology, algorithms are frequently contrasted with heuristics . Both can be useful when problem-solving, but it is important to understand the differences between them.

What Is a Heuristic?

A heuristic is a mental shortcut that allows people to quickly make judgments and solve problems.

These mental shortcuts are typically informed by our past experiences and allow us to act quickly. However, heuristics are really more of a rule-of-thumb; they don't always guarantee a correct solution.

So how do you determine when to use a heuristic and when to use an algorithm? When problem-solving, deciding which method to use depends on the need for either accuracy or speed.

When to Use an Algorithm

If complete accuracy is required, it is best to use an algorithm. By using an algorithm, accuracy is increased and potential mistakes are minimized.

If you are working in a situation where you absolutely need the correct or best possible answer, your best bet is to use an algorithm. When you are solving problems for your math homework, you don't want to risk your grade on a guess.

By following an algorithm, you can ensure that you will arrive at the correct answer to each problem.

When to Use a Heuristic

On the other hand, if time is an issue, then it may be best to use a heuristic. Mistakes may occur, but this approach allows for speedy decisions when time is of the essence.

Heuristics are more commonly used in everyday situations, such as figuring out the best route to get from point A to point B. While you could use an algorithm to map out every possible route and determine which one would be the fastest, that would be a very time-consuming process. Instead, your best option would be to use a route that you know has worked well in the past.

A Word From Verywell

Psychologists who study problem-solving have described two main processes that people utilize to reach conclusions: algorithms and heuristics. Knowing which approach to use is important because these two methods can vary in terms of speed and accuracy.

While each situation is unique, you may want to use an algorithm when being accurate is the primary concern. But if time is of the essence, then an algorithm is likely not the best choice.

Lang JM, Ford JD, Fitzgerald MM. An algorithm for determining use of trauma-focused cognitive-behavioral therapy . Psychotherapy (Chic) . 2010;47(4):554-69. doi:10.1037/a0021184

Bobadilla-Suarez S, Love BC. Fast or frugal, but not both: decision heuristics under time pressure . J Exp Psychol Learn Mem Cogn . 2018;44(1):24-33. doi:10.1037/xlm0000419

By Kendra Cherry Kendra Cherry, MS, is an author and educational consultant focused on helping students learn about psychology.

By clicking “Accept All Cookies”, you agree to the storing of cookies on your device to enhance site navigation, analyze site usage, and assist in our marketing efforts.

Study.com

In order to continue enjoying our site, we ask that you confirm your identity as a human. Thank you very much for your cooperation.

An Introduction to Problem-Solving using Search Algorithms for Beginners

This article was published as a part of the  Data Science Blogathon

In computer science, problem-solving refers to artificial intelligence techniques, including various techniques such as forming efficient algorithms, heuristics, and performing root cause analysis to find desirable solutions.

The basic crux of artificial intelligence is to solve problems just like humans.

Examples of Problems in Artificial Intelligence

In today’s fast-paced digitized world, artificial intelligence techniques are used widely to automate systems that can use the resource and time efficiently. Some of the well-known problems experienced in everyday life are games and puzzles. Using AI techniques, we can solve these problems efficiently. In this sense, some of the most common problems resolved by AI are

Table of Contents

Problem solving techniques.

Types of search algorithms

Uninformed search algorithms, comparison of various uninformed search algorithms, informed search algorithms, comparison of uninformed and informed search algorithms.

In artificial intelligence, problems can be solved by using searching algorithms, evolutionary computations, knowledge representations, etc.

In this article, I am going to discuss the various searching techniques that are used to solve a problem.

In general, searching is referred to as finding information one needs.

The process of problem-solving using searching consists of the following steps.

Let’s discuss some of the essential properties of search algorithms.

Properties of search algorithms

Completeness.

A search algorithm is said to be complete when it gives a solution or returns any solution for a given random input.

If a solution found is best (lowest path cost) among all the solutions identified, then that solution is said to be an optimal one.

Time complexity

The time taken by an algorithm to complete its task is called time complexity. If the algorithm completes a task in a lesser amount of time, then it is an efficient one.

Space complexity

It is the maximum storage or memory taken by the algorithm at any time while searching.

These properties are also used to compare the efficiency of the different types of searching algorithms.

Now let’s see the types of the search algorithm.

Based on the search problems, we can classify the search algorithm as

The uninformed search algorithm does not have any domain knowledge such as closeness, location of the goal state, etc. it behaves in a brute-force way. It only knows the information about how to traverse the given tree and how to find the goal state. This algorithm is also known as the Blind search algorithm or Brute -Force algorithm.

The uninformed search strategies are of six types.

Let’s discuss these six strategies one by one.

1. Breadth-first search

It is of the most common search strategies. It generally starts from the root node and examines the neighbor nodes and then moves to the next level. It uses First-in First-out (FIFO) strategy as it gives the shortest path to achieving the solution.

BFS is used where the given problem is very small and space complexity is not considered.

Now, consider the following tree.

Breadth-First search | Problem-Solving using AI

Source: Author

Here, let’s take node A as the start state and node F as the goal state.

The BFS algorithm starts with the start state and then goes to the next level and visits the node until it reaches the goal state.

In this example, it starts from A and then travel to the next level and visits B and C and then travel to the next level and visits D, E, F and G. Here, the goal state is defined as F. So, the traversal will stop at F.

Traversal in BFS

The path of traversal is:

A —-> B —-> C —-> D —-> E —-> F

Let’s implement the same in python programming.

Python Code:

Advantages of BFS

Disadvantages of BFS

2. Depth-first search

The depth-first search uses Last-in, First-out (LIFO) strategy and hence it can be implemented by using stack. DFS uses backtracking. That is, it starts from the initial state and explores each path to its greatest depth before it moves to the next path.

DFS will follow

Root node —-> Left node —-> Right node

Now, consider the same example tree mentioned above.

Here, it starts from the start state A and then travels to B and then it goes to D. After reaching D, it backtracks to B. B is already visited, hence it goes to the next depth E and then backtracks to B. as it is already visited, it goes back to A. A is already visited. So, it goes to C and then to F. F is our goal state and it stops there.

DFS Example | Problem-Solving using AI

A —-> B —-> D —-> E —-> C —-> F

The output path is as follows.

Output Snippet

Advantages of DFS

Disadvantages of DFS

3. Depth-limited search

Depth-limited works similarly to depth-first search. The difference here is that depth-limited search has a pre-defined limit up to which it can traverse the nodes. Depth-limited search solves one of the drawbacks of DFS as it does not go to an infinite path.

DLS ends its traversal if any of the following conditions exits.

Standard Failure

It denotes that the given problem does not have any solutions.

Cut off Failure Value

It indicates that there is no solution for the problem within the given limit.

Now, consider the same example.

Let’s take A as the start node and C as the goal state and limit as 1.

The traversal first starts with node A and then goes to the next level 1 and the goal state C is there. It stops the traversal.

Depth-limited search example | Problem-Solving using AI

A —-> C

If we give C as the goal node and the limit as 0, the algorithm will not return any path as the goal node is not available within the given limit.

If we give the goal node as F and limit as 2, the path will be A, C, F.

Let’s implement DLS.

When we give C as goal node and 1 as limit the path will be as follows.

how to solve problems using algorithms

Advantages of DLS

Disadvantages of DLS

4. Iterative deepening depth-first search

Iterative deepening depth-first search is a combination of depth-first search and breadth-first search. IDDFS find the best depth limit by gradually adding the limit until the defined goal state is reached.

Let me try to explain this with the same example tree.

Consider, A as the start node and E as the goal node. Let the maximum depth be 2.

The algorithm starts with A and goes to the next level and searches for E. If not found, it goes to the next level and finds E.

Iterative deepening depth-first search example

The path of traversal is

A —-> B —-> E

Let’s try to implement this.

The path generated is as follows.

Output snippet

Advantages of IDDFS

Disadvantages of IDDFS

5. Bidirectional search

The bidirectional search algorithm is completely different from all other search strategies. It executes two simultaneous searches called forward-search and backwards-search and reaches the goal state. Here, the graph is divided into two smaller sub-graphs. In one graph, the search is started from the initial start state and in the other graph, the search is started from the goal state. When these two nodes intersect each other, the search will be terminated.

Bidirectional search requires both start and goal start to be well defined and the branching factor to be the same in the two directions.

Consider the below graph.

Bidirectional Search Example | Problem-Solving using AI

Here, the start state is E and the goal state is G. In one sub-graph, the search starts from E and in the other, the search starts from G. E will go to B and then A. G will go to C and then A. Here, both the traversal meets at A and hence the traversal ends.

Bidirectional Search example | Problem-Solving using AI

E —-> B —-> A —-> C —-> G

Let’s implement the same in Python.

The path is generated as follows.

Output snippet

Advantages of bidirectional search

Disadvantages of bidirectional search

6. Uniform cost search

Uniform cost search is considered the best search algorithm for a weighted graph or graph with costs. It searches the graph by giving maximum priority to the lowest cumulative cost. Uniform cost search can be implemented using a priority queue.

Consider the below graph where each node has a pre-defined cost.

Uniform Cost Search example | Problem-Solving using AI

Here, S is the start node and G is the goal node.

From S, G can be reached in the following ways.

S, A, E, F, G -> 19

S, B, E, F, G -> 18

S, B, D, F, G -> 19

S, C, D, F, G -> 23

Here, the path with the least cost is S, B, E, F, G.

Uniform cost search example | Problem-Solving using AI

Let’s implement UCS in Python.

The optimal output path is generated.

Code Snippet

Advantages of UCS

Disadvantages of UCS

Now, let me compare the six different uninformed search strategies based on the time complexity.

This is all about uninformed search algorithms.

Let’s take a look at informed search algorithms.

The informed search algorithm is also called heuristic search or directed search. In contrast to uninformed search algorithms, informed search algorithms require details such as distance to reach the goal, steps to reach the goal, cost of the paths which makes this algorithm more efficient.

Here, the goal state can be achieved by using the heuristic function.

The heuristic function is used to achieve the goal state with the lowest cost possible. This function estimates how close a state is to the goal.

Let’s discuss some of the informed search strategies.

1. Greedy best-first search algorithm

Greedy best-first search uses the properties of both depth-first search and breadth-first search. Greedy best-first search traverses the node by selecting the path which appears best at the moment. The closest path is selected by using the heuristic function.

Consider the below graph with the heuristic values.

Greedy best-first search algorithm example | Problem-Solving using AI

Here, A is the start node and H is the goal node.

Greedy best-first search first starts with A and then examines the next neighbour B and C. Here, the heuristics of B is 12 and C is 4. The best path at the moment is C and hence it goes to C. From C, it explores the neighbours F and G. the heuristics of F is 8 and G is 2. Hence it goes to G. From G, it goes to H whose heuristic is 0 which is also our goal state.

Path of traversal in Greedy best-first search algorithm | Problem-Solving using AI

A —-> C —-> G —-> H

Let’s try this with Python.

The output path with the lowest cost is generated.

Output snippet

The time complexity of Greedy best-first search is O(b m ) in worst cases.

Advantages of Greedy best-first search

Disadvantages of Greedy best-first search

Next, let’s discuss the other informed search algorithm called the A* search algorithm.

2. A* search algorithm

A* search algorithm is a combination of both uniform cost search and greedy best-first search algorithms. It uses the advantages of both with better memory usage. It uses a heuristic function to find the shortest path. A* search algorithm uses the sum of both the cost and heuristic of the node to find the best path.

Consider the following graph with the heuristics values as follows.

A* search example | Problem-Solving using AI

Let A be the start node and H be the goal node.

First, the algorithm will start with A. From A, it can go to B, C, H.

Note the point that A* search uses the sum of path cost and heuristics value to determine the path.

Here, from A to B, the sum of cost and heuristics is 1 + 3 = 4.

From A to C, it is 2 + 4 = 6.

From A to H, it is 7 + 0 = 7.

Here, the lowest cost is 4 and the path A to B is chosen. The other paths will be on hold.

Now, from B, it can go to D or E.

From A to B to D, the cost is 1 + 4 + 2 = 7.

From A to B to E, it is 1 + 6 + 6 = 13.

The lowest cost is 7. Path A to B to D is chosen and compared with other paths which are on hold.

Here, path A to C is of less cost. That is 6.

Hence, A to C is chosen and other paths are kept on hold.

From C, it can now go to F or G.

From A to C to F, the cost is 2 + 3 + 3 = 8.

From A to C to G, the cost is 2 + 2 + 1 = 5.

The lowest cost is 5 which is also lesser than other paths which are on hold. Hence, path A to G is chosen.

From G, it can go to H whose cost is 2 + 2 + 2 + 0 = 6.

Here, 6 is lesser than other paths cost which is on hold.

Also, H is our goal state. The algorithm will terminate here.

Path of traversal in A* | Problem-Solving using AI

Let’s try this in Python.

The output is given as

Output snippet

The time complexity of the A* search is O(b^d) where b is the branching factor.

Advantages of A* search algorithm

Disadvantages of A* search algorithm

Now, let’s compare uninformed and informed search strategies.

Uninformed search is also known as blind search whereas informed search is also called heuristics search. Uniformed search does not require much information. Informed search requires domain-specific details. Compared to uninformed search, informed search strategies are more efficient and the time complexity of uninformed search strategies is more. Informed search handles the problem better than blind search.

Search algorithms are used in games, stored databases, virtual search spaces, quantum computers, and so on. In this article, we have discussed some of the important search strategies and how to use them to solve the problems in AI and this is not the end. There are several algorithms to solve any problem. Nowadays, AI is growing rapidly and applies to many real-life problems. Keep learning! Keep practicing!

how to solve problems using algorithms

About the Author

Dhanya thailappan.

Data Science and AI enthusiast

Our Top Authors

Rahul Shah

Download Analytics Vidhya App for the Latest blog/Article

Leave a reply your email address will not be published. required fields are marked *.

Notify me of follow-up comments by email.

Notify me of new posts by email.

Top Resources

how to solve problems using algorithms

30 Best Data Science Books to Read in 2023

how to solve problems using algorithms

How to Read and Write With CSV Files in Python:..

how to solve problems using algorithms

Understand Random Forest Algorithms With Examples (Updated 2023)

how to solve problems using algorithms

Feature Selection Techniques in Machine Learning (Updated 2023)

Welcome to India's Largest Data Science Community

Back welcome back :), don't have an account yet register here, back start your journey here, already have an account login here.

A verification link has been sent to your email id

If you have not recieved the link please goto Sign Up page again

back Please enter the OTP that is sent to your registered email id

Back please enter the otp that is sent to your email id, back please enter your registered email id.

This email id is not registered with us. Please enter your registered email id.

back Please enter the OTP that is sent your registered email id

Please create the new password here, privacy overview.

Logo for TRU Pressbooks

8.2 Problem-Solving: Heuristics and Algorithms

Learning objectives.

When faced with a problem to solve, should you go with intuition or with more measured, logical reasoning? Obviously, we use both of these approaches. Some of the decisions we make are rapid, emotional, and automatic. Daniel Kahneman (2011) calls this “fast” thinking. By definition, fast thinking saves time. For example, you may quickly decide to buy something because it is on sale; your fast brain has perceived a bargain, and you go for it quickly. On the other hand, “slow” thinking requires more effort; applying this in the same scenario might cause us not to buy the item because we have reasoned that we don’t really need it, that it is still too expensive, and so on. Using slow and fast thinking does not guarantee good decision-making if they are employed at the wrong time. Sometimes it is not clear which is called for, because many decisions have a level of uncertainty built into them. In this section, we will explore some of the applications of these tendencies to think fast or slow.

We will look further into our thought processes, more specifically, into some of the problem-solving strategies that we use. Heuristics are information-processing strategies that are useful in many cases but may lead to errors when misapplied. A heuristic is a principle with broad application, essentially an educated guess about something. We use heuristics all the time, for example, when deciding what groceries to buy from the supermarket, when looking for a library book, when choosing the best route to drive through town to avoid traffic congestion, and so on. Heuristics can be thought of as aids to decision making; they allow us to reach a solution without a lot of cognitive effort or time.

The benefit of heuristics in helping us reach decisions fairly easily is also the potential downfall: the solution provided by the use of heuristics is not necessarily the best one. Let’s consider some of the most frequently applied, and misapplied, heuristics in the table below.

In many cases, we base our judgments on information that seems to represent, or match, what we expect will happen, while ignoring other potentially more relevant statistical information. When we do so, we are using the representativeness heuristic . Consider, for instance, the data presented in the table below. Let’s say that you went to a hospital, and you checked the records of the babies that were born on that given day. Which pattern of births do you think you are most likely to find?

Most people think that list B is more likely, probably because list B looks more random, and matches — or is “representative of” — our ideas about randomness, but statisticians know that any pattern of four girls and four boys is mathematically equally likely. Whether a boy or girl is born first has no bearing on what sex will be born second; these are independent events, each with a 50:50 chance of being a boy or a girl. The problem is that we have a schema of what randomness should be like, which does not always match what is mathematically the case. Similarly, people who see a flipped coin come up “heads” five times in a row will frequently predict, and perhaps even wager money, that “tails” will be next. This behaviour is known as the gambler’s fallacy . Mathematically, the gambler’s fallacy is an error: the likelihood of any single coin flip being “tails” is always 50%, regardless of how many times it has come up “heads” in the past.

The representativeness heuristic may explain why we judge people on the basis of appearance. Suppose you meet your new next-door neighbour, who drives a loud motorcycle, has many tattoos, wears leather, and has long hair. Later, you try to guess their occupation. What comes to mind most readily? Are they a teacher? Insurance salesman? IT specialist? Librarian? Drug dealer? The representativeness heuristic will lead you to compare your neighbour to the prototypes you have for these occupations and choose the one that they seem to represent the best. Thus, your judgment is affected by how much your neibour seems to resemble each of these groups. Sometimes these judgments are accurate, but they often fail because they do not account for base rates , which is the actual frequency with which these groups exist. In this case, the group with the lowest base rate is probably drug dealer.

Our judgments can also be influenced by how easy it is to retrieve a memory. The tendency to make judgments of the frequency or likelihood that an event occurs on the basis of the ease with which it can be retrieved from memory is known as the availability heuristic (MacLeod & Campbell, 1992; Tversky & Kahneman, 1973). Imagine, for instance, that I asked you to indicate whether there are more words in the English language that begin with the letter “R” or that have the letter “R” as the third letter. You would probably answer this question by trying to think of words that have each of the characteristics, thinking of all the words you know that begin with “R” and all that have “R” in the third position. Because it is much easier to retrieve words by their first letter than by their third, we may incorrectly guess that there are more words that begin with “R,” even though there are in fact more words that have “R” as the third letter.

The availability heuristic may explain why we tend to overestimate the likelihood of crimes or disasters; those that are reported widely in the news are more readily imaginable, and therefore, we tend to overestimate how often they occur. Things that we find easy to imagine, or to remember from watching the news, are estimated to occur frequently. Anything that gets a lot of news coverage is easy to imagine. Availability bias does not just affect our thinking. It can change behaviour. For example, homicides are usually widely reported in the news, leading people to make inaccurate assumptions about the frequency of murder. In Canada, the murder rate has dropped steadily since the 1970s (Statistics Canada, 2018), but this information tends not to be reported, leading people to overestimate the probability of being affected by violent crime. In another example, doctors who recently treated patients suffering from a particular condition were more likely to diagnose the condition in subsequent patients because they overestimated the prevalence of the condition (Poses & Anthony, 1991).

The anchoring and adjustment heuristic is another example of how fast thinking can lead to a decision that might not be optimal. Anchoring and adjustment is easily seen when we are faced with buying something that does not have a fixed price. For example, if you are interested in a used car, and the asking price is $10,000, what price do you think you might offer? Using $10,000 as an anchor, you are likely to adjust your offer from there, and perhaps offer $9000 or $9500. Never mind that $10,000 may not be a reasonable anchoring price. Anchoring and adjustment does not just happen when we’re buying something. It can also be used in any situation that calls for judgment under uncertainty, such as sentencing decisions in criminal cases (Bennett, 2014), and it applies to groups as well as individuals (Rutledge, 1993).

In contrast to heuristics, which can be thought of as problem-solving strategies based on educated guesses, algorithms are problem-solving strategies that use rules. Algorithms are generally a logical set of steps that, if applied correctly, should be accurate. For example, you could make a cake using heuristics — relying on your previous baking experience and guessing at the number and amount of ingredients, baking time, and so on — or using an algorithm. The latter would require a recipe which would provide step-by-step instructions; the recipe is the algorithm. Unless you are an extremely accomplished baker, the algorithm should provide you with a better cake than using heuristics would. While heuristics offer a solution that might be correct, a correctly applied algorithm is guaranteed to provide a correct solution. Of course, not all problems can be solved by algorithms.

As with heuristics, the use of algorithmic processing interacts with behaviour and emotion. Understanding what strategy might provide the best solution requires knowledge and experience. As we will see in the next section, we are prone to a number of cognitive biases that persist despite knowledge and experience.

Key Takeaways

Bennett, M. W. (2014). Confronting cognitive ‘anchoring effect’ and ‘blind spot’ biases in federal sentencing: A modest solution for reforming and fundamental flaw. Journal of Criminal Law and Criminology , 104 (3), 489-534.

Kahneman, D. (2011). Thinking, fast and slow. New York, NY: Farrar, Straus and Giroux.

MacLeod, C., & Campbell, L. (1992). Memory accessibility and probability judgments: An experimental evaluation of the availability heuristic.  Journal of Personality and Social Psychology, 63 (6), 890–902.

Poses, R. M., & Anthony, M. (1991). Availability, wishful thinking, and physicians’ diagnostic judgments for patients with suspected bacteremia.  Medical Decision Making,  11 , 159-68.

Rutledge, R. W. (1993). The effects of group decisions and group-shifts on use of the anchoring and adjustment heuristic. Social Behavior and Personality, 21 (3), 215-226.

Statistics Canada. (2018). Ho micide in Canada, 2017 . Retrieved from https://www150.statcan.gc.ca/n1/en/daily-quotidien/181121/dq181121a-eng.pdf

Tversky, A., & Kahneman, D. (1973). Availability: A heuristic for judging frequency and probability.  Cognitive Psychology, 5 , 207–232.

Psychology - 1st Canadian Edition by Sally Walters is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License , except where otherwise noted.

Share This Book

Javarevisited

Javarevisited

May 11, 2020

Top 20 Algorithms Coding Problems for Programming Interviews with Solutions

Preparing for coding interviews here are 20+ algorithms problems you can practice. this list included questions on essential searching and sorting algorithms like binary search, quick sort, counting sort, etc..

Hello All, If you are preparing for Programming job interviews or looking for a new job, then you know that it’s not an easy process. You got to be lucky to get the call and make it to the first round of interviews, not just when you are a beginner but at any stage of your career.

But, Yes, it is the most difficult at the beginner level when you are searching for your first job.

That’s why you can’t just take your chance lightly. You got to be prepared to grab that chance and for that, you must know that is expected from you on the interview. What is asked, what topics should you prepare, etc?

I have blogged a lot about what you can find helpful articles in this blog but to recap let me tell you that apart from data structure questions , System Design Questions , and Programming language-specific questions like Java , C++ , or Scala , most of the programming job interviews also ask algorithm based questions.

These are based upon common searching and sorting algorithms like String algorithms , binary search , graph algorithms , etc.

It’s important that you practice these Algorithms based questions because even though they seem obvious and easy, sometimes they become tricky to solve in the actual interview, especially if you have never coded them by yourself.

Practising these problems before interview not only makes you familiar with them but also gives you more confidence in explaining the solution to the interviewer, which plays a very important role in your selection.

It also makes you ready for any twisted questions, and alternative problems like Interviewers often like to ask you to solve a particular coding problem using Recursion or Iteration .

Sometimes, if you use a data structure like the one I have used in finding duplicate characters on String , they will ask you to solve that problem without using the Set data structure. Those are just some common examples, and that’s why practice matters a lot.

Btw, if you are a complete beginner in the world of Data Structure and Algorithms, then I suggest you first go through a comprehensive Algorithm course like Data Structures and Algorithms: Deep Dive Using Java on Udemy which will not only teach you basic data structure and algorithms but also how to use them on the real world and how to solve coding problems using them.

On the other hand, if you like to read books or prefer books over online courses, then you must read a comprehensive book like Introduction to Algorithms by Thomas H. Cormen to get an understanding of common Computer Science Algorithms like Searching, Sorting, Cryptography, Graph Algorithms and some common ones like Fourier Transform.

20+ Searching and Sorting Algorithms Questions from Coding Interviews

Anyway, here are some of the frequently asked Searching and Sorting Algorithms questions from Interviews. I have linked the solution, but you should try to solve the problem before looking at the solution.

The purpose of this article is that you should know how to solve these problems on your own, but, yes, if you got stuck and want to compare your solution, you can see the solution.

Searching Algorithms based Coding Problems

Let’s first start with basic search algorithms like linear search, binary search, level order search, and depth-first search algorithms.

1. Can you implement a Binary Search Algorithm? ( solution )

It’s easy, binary search is a divide and conquer algorithm, where the problem is divided into sub-problem, and those are solved. It’s a search algorithm, which means it is used to find things like a number in an integer array or an item in a catalog.

The easiest way to implement a binary search algorithm is by using Recursion, which is what the solution link contains, but you should try it yourself before seeing the solution.

One of the worth noting is that the input must be sorted, I mean you can only implement binary search in a sorted array .

2. Write a program to implement a Linear Search Algorithm? ( solution )

It is even easier than binary search, all you need to do is go through all elements in the array using a for loop or recursive method and compare each element with the one you want to search. When an element matches, you either return the index or depend upon your requirement.

For example, if you are writing a contains() method you can return true or false to indicate whether an element is present in the array or not. Since you need to scan the whole array to find the element, the time complexity of this algorithm is O(n) .

3. Can you implement a Binary search Algorithm without recursion? ( solution )

You might know that you can replace a recursive algorithm to an iterative one by using a loop and sometimes using a Stack data structure. For binary search also you can do this; just divide the array and compare the middle element until you find the target element or there is no more element into an array.

If the target element is greater than middle than you got to move towards the right, or otherwise towards left.

Btw, if you have trouble understanding recursive algorithms or converting a recursive one to an iterative one, then I suggest you go through a good online course like Algorithms and Data Structures — Part 1 and Part 2 in Pluralsight to learn fundamentals better.

These courses will also teach you about how to calculate time and space complexity, which is very important from both the Coding Interview perspective as well as improving the performance of an Algorithm.

By the way, you would need a Pluralsight membership to join this course which costs around $29 per month or $299 per year (14% discount). I highly recommend this subscription to all programmers as it provides instant access to more than 7000+ online courses to learn any tech skill.

Alternatively, you can also use their 10-day-free-pass to watch this course for FREE.

4. Write Code to implement Level Order Search in a Binary Tree? (solution)

In level order search, you first visit sibling nodes then go down into the next level. You can use a Queue to implement a level order search in a binary tree.

And, if you are really serious about doing well, you can also check this list of courses to crack your programming job interviews

100+ Coding Interview Questions for Programmers

Solve these frequently asked coding problems to do well on your next programming job interviews..

codeburst.io

5. What is Depth First Search Algorithm for a binary tree? (solution)

It’s another popular searching algorithm that is mainly used in trees and graphs. This algorithm first visits nodes in depth before searching at the same level; that’s why the name Depth-first search algorithm.

It’s tricky to implement, but you can use a Stack to implement DFS or Depth-first search algorithm. If you need more information on this topic, I suggest you check the Grokking Algorithms book by Aditya Bhargava; his explanation is probably the best explanation of this topic

Sorting Algorithms based Coding Problems

Now we have seen some coding problems based upon search algorithms, let’s dive into coding problems based on sorting algorithms:

6. Implement the Bubble sort Algorithm? ( solution )

Isn’t this was the first sorting algorithm you learn? Well, I did, and that’s why I remember that bubble sort is about comparing each number with every other number in an array so that after each pass, the largest or smallest element bubble up to the top.

I mean, the number has been found it’s placed in the sorting order. This is one of the fundamental sorting algorithms, and most of us started learning about sorting using this algorithm.

The time complexity of this is O(n ^2) which makes it unusable for a large set of numbers but it does well for a small set of numbers. If you want to learn more, you can check any of these free data structure and algorithms courses on freeCodeCamp

Top 10 Free Data Structure and Algorithms Courses for Beginners — Best of Lot

Algorithms and data structure are two of the most fundamentals and essential topics from computer science, which is…, 7. difference between a stable and unstable sorting algorithm ( answer ).

This one was a tricky concept that I didn’t know until long ago. I haven’t come across any practical use case of this one yet, but just knowing the concept is Ok from the interview perspective.

In a stable sorting algorithm, the order of the same element remains the same even after sorting, but during the unstable sorting algorithm, these changes.

A good example is a quicksort and mergesort, where the former is unstable while latter is a stable algorithm.

8. How is an iterative quicksort algorithm implemented? ( solution )

Obviously without recursion:-). If you remember, I have told you before that you can use a Stack to convert a recursive algorithm into an iterative one and that’s what you can do as well to implement the Quicksort algorithm without recursion.

Btw, if you have trouble calculating and understanding the time and space complexity of algorithms, then you should see a course like Data Structures & Algorithms — Interview to understand them better before going for an interview.

9. How do you implement a counting sort algorithm? ( solution )

Just like we have done with other O(n) sorting algorithms like Radix sort and Bucket sort.

If you don’t know, Counting sort is another integer sorting algorithm for sorting a collection of objects according to keys that are small integers.

It has O(n) time complexity, which makes it faster than the likes of Quicksort and Mergesort for a particular set of input. See the solution for more details.

10. How do you swap two numbers without using the third variable? ( solution )

Another tricky question which is easy if you know the trick :-) Well you can swap two numbers without using a temporary or third variable if you can store the sum of numbers in one number and then minus the sum with another number something like

a = 3; b = 5;

a = a + b; //8 b = a — b; // 3 a = a — b; //5

now you have a = 5 and b = 3, so numbers are swapped without using a third or temp variable.

11. How is a radix sort algorithm implemented? ( solution )

This is another integer sorting algorithm with O(n) time complexity. As per Wikipedia, Radix sort is a non-comparative sorting algorithm that sorts data with integer keys by grouping keys by the individual digits, which share the same significant position and value.

You can further see Algorithms, Part I , and Part II by Robert Sedgewick on Coursera to learn more about these or liner sorting algorithms. The course is free for learning and exploring, but you need to pay if you also want a certification.

And, if you find Coursera courses useful, which they are because they are created by reputed companies like Google , IBM , Amazon , and the best universities around the world, I suggest you join the Coursera Plus , a subscription plan from Coursera

This single subscription gives you unlimited access to their most popular courses , specialization , professional certificate , and guided projects . It cost around $399/year but its completely worth of your money as you get unlimited certificates .

12. How do you implement an insertion sort algorithm? ( solution )

Have you ever arranged the deck of cards, or maybe shirts in your cupboard? What is common between those two things? Well, you put the next card or shirt into their proper position, or, should I say you insert the next element in its proper position. That’s the insertion sort for you.

Miscellaneous Algorithms based Problems from Tech interviews

Now, let’s see a few more coding problems which are based upon different algorithms.

13. Write the Algorithm to check if two rectangles overlap with each other? ( solution )

This is a tricky Algorithm question, but if you have to listen to your teacher in your 2D Maths class, then you can solve this problem. There is another trick, check for all the conditions when rectangles will not overlap, and if any condition is false, it means both rectangles are overlapping with each other. For example, if the upper side of one rectangle is below the lower side of other rectangles, then they won’t overlap as they are vertically aligned.

Btw, if you find this question tough to solve, I suggest you take a look at the Grokking the Coding Interview: Patterns for Coding Questions course on Educative, an interactive portal for coding interviews to learn some 16 useful coding patterns like Sliding Window , Two Pointers, Fast and Slow Pointers, Merge Intervals, Cyclic Sort, and Top K elements that can help you to solve zones of frequently asked coding problems.

14. How is a merge sort algorithm implemented? ( solution )

Similar to Quicksort, merge sort is also a divide and conquers algorithm, which means you keep the problem until you can sort the smallest of them.

For example, to sort an array of numbers , you divide the array into smaller parts until you know how to sort them like an array with one or zero elements is already sorted. Once you sort small arrays, you merge them to get the final result.

The only difference between Quicksort and Mergesort is that mergesort is stable while Quicksort is not-stable . This means equal elements retain their spot before and after sorting.

Another worth noting difference is that even though both have average time, it’s better to use quicksort than mergesort because Quicksort takes less time for the same number of input, the constant factor is less in Quicksort than merge sort.

15. How do you implement a bucket sort algorithm? ( solution )

The Bucket sort is another awesome algorithm that can sort an array without even comparing elements. It’s known as a non-comparison sorting algorithm and can give O(n) performance for the selected input.

If you don’t know about the non-comparison-based sorting Algorithm, please see Introduction to Algorithms book.

16. Write Algorithms to Check if Two String are Anagram ( Solution )

An anagram is something where length and character match but not the order like Army and Mary , both have the same number of characters.

One trick is to solve this problem is to sort the character array and check if they are the same or not.

17. Implement the QuickSort Algorithm in your Favorite Programing language? ( solution )

This one is a very easy sorting algorithm, but only if you have practiced, if not, then you may lose your way. Remember, Quicksort is a divide and conquer algorithm , which means you keep dividing array, also known as partitioning . Then you solve the problem at the smallest level, also known as a base case like when your array contains just one or zero elements.

19. Difference between Comparison and Non-Comparison Sorting Algorithms? ( answer )

As the name suggests, in comparison-based sorting algorithms, you must compare elements to sort like quicksort, but in non-comparison-based sorting algorithms like Counting sort , you can sort elements without comparing them. Surprised?

Well yes, then I suggest you check out this course to learn more about sorting algorithms like Radix Sort, Counting Sort, and Bucket Sort. You can further see Data Structures and Algorithms: Deep Dive if you want to learn more about these sorting algorithms.

19. How to check if two String is rotations of each other? ( solution )

There is a simple trick to solve this problem, just concatenate the string with itself and check if the rotation exists there. You can do that by using indexOf or substring method. If the concatenated String contains rotation, then the given String is a rotation of former.

20. Implement Sieve of Eratosthenes Algorithms for Prime Number? ( solution )

This is one of the tough algorithms to implement, especially if you don’t remember it :-) Sometimes, the interviewer gives you the explanation, but other times, you need to remember it.

I hope these 20 questions should be enough to get you going on your preparation for Algorithms for Coding interviews. If you need more such coding questions, you can take help from books like Cracking The Code Interview by Gayle Laakmann McDowell which contains 189+ Programming questions and solutions. A good book to prepare for programming job interviews in a short time.

By the way, the more questions you solve in practice, the better your preparation will be. So, if you think this list of questions is not enough and you need more, then check out these additional 50 programming questions for telephone interviews and these books and courses for more thorough preparation.

Now You’re Ready for the Coding Interview

These are some of the most common questions outside of data structure and algorithms that help you to do really well in your interview.

I have also shared a lot of these questions on my blog , so if you are really interested, you can always go there and search for them.

These common coding, data structure, and algorithms questions are the ones you need to know to successfully interview with any company, big or small, for any level of programming job.

If you are looking for a programming or software development job, you can start your preparation with this list of courses to learn patterns, tips, and tricks to solve coding problems

Resources to Prepare for Tech Interviews

This list provides good topics to prepare and also helps assess your preparation to find out your areas of strength and weakness.

Good knowledge of data structure and algorithms is important for success in coding interviews, and that’s where you should focus most of your attention.

Closing Notes

Thanks, You made it to the end of the article … Good luck with your programming interview! It’s certainly not going to be easy, but by following these searching and sorting algorithm questions, you are one step closer than others.

If you like this article, then please share it with your friends and colleagues, and don’t forget to follow javarevisited on Twitter and javinpaul and javinpaul here on Medium as well!

P. S. — If you are preparing Tech Interviews then I also suggest you go through Grokking the Coding Interview: Patterns for Coding Questions to learn 16 useful coding patterns like Sliding Window, Two Pointers, Fast and Slow Pointers, Merge Intervals, Cyclic Sort, and Top K elements that can help you to solve dozens of frequently asked coding problems.

Grokking the Coding Interview: Patterns for Coding Questions - Learn Interactively

Coding interviews are getting harder every day. a few years back, brushing up on key data structures and going through….

www.educative.io

Other Data Structure and Algorithms Articles from Medium

50+ data structure and algorithms interview questions for programmers, there are a lot of computer science graduates and programmers applying for programming, coding, and software…, 10 data structure, algorithms, and programming courses to crack any coding interview, many junior developers dream of making it at one of the larger tech companies, but, to be honest with you, getting your…, 10 best books for data structure and algorithms for beginners in java, c/c++, and python, algorithms are language agnostic, and any programmer worth their salt should be able to convert them to code in their…, more from javarevisited.

A humble place to learn Java and Programming better.

About Help Terms Privacy

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store

I am Java programmer, blogger, working on Java, J2EE, UNIX, FIX Protocol. I share Java tips on http://javarevisited.blogspot.com and http://java67.com

Text to speech

An algorithm for split equilibrium and fixed-point problems using inertial extragradient techniques

Computational and Applied Mathematics volume  42 , Article number:  103 ( 2023 ) Cite this article

32 Accesses

Metrics details

We study in this article, split equilibrium fixed-point problems involving pseudomonotone bifunctions which satisfy Lipschitz-type continuous condition and nonexpansive mappings, respectively, in real Hilbert spaces. In order to solve this problem, we propose an inertial extragradient algorithm and establish strong convergence theorem using the sequence of the algorithm under mild conditions. A numerical example given demonstrates that our algorithm is efficient and is superior to the algorithm studied by Narin (J Ineq Appl 2019:137, 2019).

This is a preview of subscription content, access via your institution .

Access options

Buy single article.

Instant access to the full article PDF.

Price excludes VAT (USA) Tax calculation will be finalised during checkout.

Rent this article via DeepDyve.

how to solve problems using algorithms

Availability of data and materials

Not applicable.

Code availability

Available on request.

Anantachai P, Kumam P, Parin C, Shehu Y (2020) Convergence of inertia modified Krasnoselski-Mann iteration with application to image recovery. Thai J Maths 18:126–142

MATH   Google Scholar  

Anh PN (2013) A hybrid extragradient method extended to fixed point problems and equilibrium problems. Optimization 62:271–283

Article   MathSciNet   MATH   Google Scholar  

Arfat Y, Kumam P, Ngiamsunthorn PS, Khan MAA, Sarwar H, Fukhar-ud-Din H (2020) Approximation results for split equilibrium problems and fixed point problems of nonexpansive semigroup in Hilbert spaces. Adv Cont Discrete Models 2020:512

MathSciNet   MATH   Google Scholar  

Beck A, Teboulle M (2009) A fast iterative shrinkage-thresholding algorithm for linear inverse problems. SIAM J Imaging Sci 2:183–202

Blum E, Oettli W (1994) From optimization and variational inequalities to equilibrium problems. Math Program 63:123–145

Byrne C (2002) Iterative oblique projection onto convex sets and the split feasibility problem. Inverse Probl 18:441–453

Byrne C (2004) A unified treatment for some iterative algorithms in signal processing and image reconstruction. Inverse Probl 20:103–120

Censor Y, Elfving T (1994) A multiprojection algorithm using Bregman projections in product space. Numer Alg 8:221–239

Censor Y, Segal A (2009) The split common fixed point problem for directed operators. J Convex Anal 16:587–600

Censor Y, Gibali A, Reich S (2012) Algorithms for the split variational inequality problem. Numer Alg 59:301–323

Chidume CE (2009) Geometric properties of banach spaces and nonlinear iterations, vol 1965 of lecture notes in mathematics. Springer, London

Cho SY (2020) A monotone Bregman projection algorithm for fixed point and equilibrium problems in a reflexive Banach space. Filomat 34:1487–1497

Cohen G (1980) Auxiliary problem principle and decomposition of optimization problems. J Optimiz Theory Appl 32:277–305

Cohen G (1988) Auxiliary principle extended to variational inequalities. J Optimiz Theory Appl 59:325–333

Dadash V, Iyiola OS, Shehu Y (2020) The subgradient extragradient method for pseudomonotone equilibrium problems. Optimization 69(4):901–923

Enyi CD, Shehu Y, Iyiola OS, Yao JC (2022) Convergence analysis of modified inertial forward-backward splitting scheme with applications. Math Meth Appl Sci 45:3933–3948

Article   MathSciNet   Google Scholar  

Ezeora JN, Bazuaye FE (2021) Iterative approximation of split feasibility problem in real Hilbert spaces. Int J Math Anal Optim Theory Appl 7(2):30–47. https://doi.org/10.52968/28307336

Article   Google Scholar  

Ezeora JN, Jackreece PC (2021) Iterative solution of split equilibrium and fixed point problems in real Hilbert spaces. J Nonlinear Sci Appl 14:359–371

Ezeora JN, Ogbonna RC (2018) Split feasibility problem for countable family of multi-valued nonliear mappings. Mate Vesnik 70(3):233–242

Facchinei F, Pang JS (2003) Finite-dimensional variational inequalities and complementary problems. Springer, New York

Gibali A (2017) A new split inverse problem and application to least intensity feasible solutions. Pure Appl Funct Anal 2(2):243–258

Gibali A, Jolaoso LO, Mewomo OT, Taiwo A (2020) Fast and simple Bregman projection methods for solving variational inequalities and related problems in Banach spaces. Results Math 75:179

Goebel K, Kirk WA (1990) Topics in metric fixed point theory. Cambridge studies in advanced mathematics, vol 28. Cambridge University Press, Cambridge

Book   MATH   Google Scholar  

Harisa SA, Khan MAA, Mumtaz F, Farid N, Morsy A, Nisar KS, Ghaffar A (2020) Shrinking Cesaro means method for the split equilibrium and fixed point problems in Hilbert spaces. Adv Differ Equ 2020:345

He Z (2012) The split equilibrium problem and its convergence algorithms. J Inequal Appl 2012:162

Hue TT, Strodiot JJ, Nguyen VH (2004) Convergence of the approximate auxiliary problem method for solving generalized variational inequalities. J Optimiz Theory Appl 121:119–145

Iyiola OS, Enyi CD, Shehu Y (2021) Reflected three-operator splitting method for monotone inclusion problem. Optim Methods Softw 2021:1–39. https://doi.org/10.1080/10556788.2021.1924715

Article   MATH   Google Scholar  

Izuchukwu C, Ogwo GN, Mewomo OT (2022) An inertial method for solving generalized split feasibility problems over the solution set of monotone variational inclusions. Optimization 71(3):583–611

Kazmi KR, Rizvi SH (2013) Iterative approximation of a common solution of a split equilibrium problem, a variational inequality problem and a fixed point problem. J Egypt Math Soc 21:44–51

Kim DS, Dinh BV (2018) Parallel extragradient algorithms for multiple set split equilibrium problems in Hilbert spaces. Numer Alg 77:741–761

Konnov IV (2003) Application of the proximal point method to nonmonotone equilibrium problems. J Optimiz Theory Appl 119:317–333

Konnov IV (2007) Equilibrium models and variational inequalities. Elsevier, Amsterdam

Korpelevich GM (1976) Extragradient method for finding saddle points and other problems. Matecon 12:747–756

Mainge PE (2007) Approximation methods for common fixed points of nonexpansive mappings in Hilbert spaces. J Math Anal Appl 325:469–479

Mainge PE (2008) Strong convergence of projected subgradient methods for nonsmooth and nonstrictly convex minimization. Set-Valued Anal 16:899–912

Martinet B (1970) Regularisation d inequations variationelles par approximations successives. Rev Fr Automat Inf 4:154–159

Mastroeni G (2000) On auxiliary principle for equilibrium problems. Publ Dipartim Math dell’Univ Pisa 3:1244–1258

Google Scholar  

Moudafi A (1999) Proximal point algorithm extended to equilibrium problem. J Nat Geometry 15:91–100

Moudafi A (2011) Split monotone variational inclusions. J Optim Theory Appl 150:275–283

Muul D, Oettli W (1992) Convergence of an adaptive penalty scheme for finding constraint equilibria. Nonlinear Anal 18:1159–1166

Narin P, Mohsen R, Manatchanok K, Vahid D (2019) A new extragradient algorithm for split equilibrium problems and fixed point problems. J Ineq Appl 2019:137

Nesterov Y (1983) A method of solving a convex programming problem with convergence rate \(O(1/k^22)\) . Soviet Math Doklady 27:372–376

Noor MA (2003) Extragradient methods for pseudomonotone variational inequalities. J Optimiz Theory Appl 117:475–488

Noor MA (2004) Auxiliary principle technique for equilibrium problems. J Optimiz Theory Appl 122:371–386

Polyak BT (1964) Some methods of speeding up the convergence of iteration methods. Comput Math Math Phys 4:1–17

Quoc TD, Le DM, Nguyen VH (2008) Extragradient algorithms extended to equilibrium problems. Optimization 57(6):749–776

Rockafellar RT (1976) Monotone operators and the proximal point algorithm. SIAM J Control Optim 14:877–898

Shehu Y, Vuong PT, Zemkoho A (2021) An inertial extrapolation method for convex simple bilevel optimization. Optim Methods Softw 36(1):1–19

Shehu Y, Iyiola OS, Thong DV, Nguyen TCV (2021) An inertial subgradient extragradient algorithm extended to pseudomonotone equilibrium problems. Math Meth Oper Res 93:213–242

Zhao J, Yang Q (2005) Several solution methods for the split feasibility problem. Inverse Probl 21(5):1791–1799

Zhu LJ, Kuo HC, Wen CF (2021) Strong convergence results of split equilibrium problems and fixed point problems. J Math 2021:6624321. https://doi.org/10.1155/2021/6624321

Download references

Acknowledgements

The second author thanks University of Hafr Al Batin for continuous support. The authors thank deeply the reviewers for thoroughly evaluating the original manuscript and making insightful comments that helped improve the quality of the paper.

Author information

Cyril D. Enyi, Francis O. Nwawuru and Richard C. Ogbonna contributed equally to this work.

Authors and Affiliations

Department of Mathematics and Statistics, University of Port Harcourt, Port Harcourt, Nigeria

Jeremiah N. Ezeora

Department of Mathematics, University of Hafr Al Batin, Hafr Al Batin, Saudi Arabia

Cyril D. Enyi

Department of Mathematics, Chukwuemeka Odumegwu Ojukwu University, Awka, Anambra State, Nigeria

Francis O. Nwawuru

Department of Computer Science and Mathematics, Evangel University, Aka-Eze, Nigeria

Richard C. Ogbonna

You can also search for this author in PubMed   Google Scholar

Corresponding author

Correspondence to Jeremiah N. Ezeora .

Ethics declarations

Conflict of interest.

There is no conflict of interest.

Ethics approval

Consent to participate.

All the authors participated in the work.

Consent for publication

All the authors consented to publication of this work.

Additional information

Communicated by Andreas Fischer.

Publisher's Note

Springer Nature remains neutral with regard to jurisdictional claims in published maps and institutional affiliations.

Rights and permissions

Springer Nature or its licensor (e.g. a society or other partner) holds exclusive rights to this article under a publishing agreement with the author(s) or other rightsholder(s); author self-archiving of the accepted manuscript version of this article is solely governed by the terms of such publishing agreement and applicable law.

Reprints and Permissions

About this article

Cite this article.

Ezeora, J.N., Enyi, C.D., Nwawuru, F.O. et al. An algorithm for split equilibrium and fixed-point problems using inertial extragradient techniques. Comp. Appl. Math. 42 , 103 (2023). https://doi.org/10.1007/s40314-023-02244-7

Download citation

Received : 18 June 2022

Revised : 21 November 2022

Accepted : 12 February 2023

Published : 01 March 2023

DOI : https://doi.org/10.1007/s40314-023-02244-7

Share this article

Anyone you share the following link with will be able to read this content:

Sorry, a shareable link is not currently available for this article.

Provided by the Springer Nature SharedIt content-sharing initiative

Mathematics Subject Classification

Advertisement

Steps of Problem Solving in Data Structures and Algorithms

Every solution starts with a strategy, and an algorithm is a strategy for solving a coding problem. So, we must learn to design an efficient algorithm and translate this 'algorithm' into the correct code to get the job done.

But there are many coding problems available in data structures and algorithms, and most of the time, these problems are new to us. So as programmers, we need to develop ourselves as confident problem-solvers who are not intimidated by the difficulty of the given problem. 

Our long-term goal should be simple: Learn to design correct and efficient code within a given time. As we practice more and more, we will gain experience in problem-solving, and our work will become easier. Here are some essential skills that we should practice for every DSA problem:

Now, the critical question would be: Is there a well-defined, guided strategy to approach and solve a coding problem? If yes, then what are the critical steps? Let's think and explore!

Steps of problem-solving in algorithms and data structures

Step 1: Understanding the problem

Solving a problem requires a clear understanding of the problem. Unfortunately, sometimes we read only the first few lines and assume the rest of the problem or ignore this step because we have seen something similar in the past. We should view these as unfair practices and develop a clear approach to understanding problems.

During problem-solving, every small detail can help us design an efficient solution. Sometimes, a small change in the question can alter the solution approach. Taking extra time to understand the problem will give us more confidence later on. The fact is, we never want to realize halfway through that we misunderstood the problem.

It doesn't matter if we have encountered a question before or not; we should read the question several times. So, take a paper and write down everything while going through the problem. Exploring some examples will also help us clarify how many cases our algorithm can handle and the possible input-output patterns. We should also explore scenarios for large input, edge cases, and invalid input.

Sometimes, it is common for problem descriptions to suffer from these types of deficiencies:

These deficiencies may be due to the abstract explanation of the problem description in our natural languages. So, it is our responsibility to identify such deficiencies and work with the interviewer or problem provider to clarify them. We should start by seeking answers to the following questions:

Step 2: Thinking of a correct basic solution

The best approach would be to think of a correct solution that comes immediately to our mind. It does not matter even if it is an inefficient approach. Having a correct and inefficient answer is much better than an incorrect solution or significant delay in finding the solution. This could help us in so many ways:

Here are some examples of brute force patterns: three nested loops, two nested loops, solution using extra memory, solution using sorting, double traversal in the binary tree, considering all sub-arrays or substrings, exhaustive search, etc.

After thinking and communicating the brute force idea, the interviewer may ask for its time and space complexity. We need to work on paper, analyze each critical operation, and write it in the form of Big-O notation. Clear conceptual idea of time and space complexity analysis is essential at this stage.

Step 3: Designing efficient solution with pseudocode

This is a stage to use the best experience of DSA problem-solving and apply various problem-solving strategies . One practical truth is: moving from a basic algorithm to the most efficient algorithm is a little difficult in a single step. Each time, we need to optimize the previous algorithm and stop when there is no further optimization possible. Revisiting the problem description and looking for some additional information can help a lot in further optimization. For example:

The idea would be simple: we should learn the use case of efficient problem-solving patterns on various data structures. Continuously thinking, analyzing, and looking for a better solution is the core idea. 

Here are some best examples of problems where several levels of optimisations are feasible. Practicing such types of coding questions helps a lot in building confidence.

Find equilibrium index of an array

Trapping rain water

Check for pair with a given sum

Find the majority element in an array

Maximum Subarray Sum

Before you jump into the end-to-end code implementation, it’s good practice to write pseudocode on paper. It would be helpful in defining code structure and critical operations. Some programmers skip this step, but writing the final code becomes easier when we have well-designed pseudocode.

Top 10 problem solving approaches in DSA to master coding interview

Step 4: Transforming pseudocode into a clean, correct, and optimized code

Finally, we need to replace each line of pseudocode with actual code in our favorite programming languages like C++, Java, Python, C#, JavaScript, etc. Never forget to test actual code with sample test data and check if the actual output is equal to the expected output. When writing code in your interviews, discuss sample data or test cases with the interviewer.

Simplifying and optimizing the code may require a few iterations of observation. We need to ask these questions once we are done writing the code: 

Enjoy learning, Enjoy coding, Enjoy algorithms!

Share feedback

Don’t fill this out if you’re human:

More blogs to explore

Subscribe our newsletter.

Subscribe to get weekly content on data structure and algorithms, machine learning, system design and oops.

Follow us on:

© 2022 Code Algorithms Pvt. Ltd.

All rights reserved.

how to solve problems using algorithms

Wuhan University Bachelor Dissertation: the Application of Evolutionary Algorithms in the Parameter Optimization of Differential Equations

rushingfox/Evolutionary-Algorithm-to-solve-the-Inverse-Problem-of-Differential-Equations

Name already in use.

Use Git or checkout with SVN using the web URL.

Work fast with our official CLI. Learn more .

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

@rushingfox

Evolutionary-Algorithm-to-solve-the-Inverse-Problem-of-Differential-Equations

This repository is the code of Jianhao Wu's Bachelor Dissertation in the School of Computer Science, Wuhan University: The Application of Evolutionary Algorithms in the Parameter Optimization of Differential Equations.

This thesis focuses on the application of evolutionary algorithms to the inverse problem of continuous function parameters for elliptic and parabolic differential equations.

Not only reproduced the old algorithm but also proposed a stepwise evolutionary algorithm based on this algorithm, i.e., the original algorithm is still used for a wide range of search activities at the early stage of evolution, and an elite variational operator designed by me is added for further parameter optimization at the later stage of evolution, which effectively improves the upper limit of the accuracy of the original algorithm and also reduces the possibility of falling into a local optimum.

What is Pseudocode? How to Use Pseudocode to Solve Coding Problems

You might be wondering what pseudocode is and why it's so useful for writing computer programs.

But before we jump into pseudocode, let's refresh our memories about what programming and coding are, in the simplest sense.

Programming is the manifestation of logic. A program is a set of instructions that defines the behaviour of your software application. Writing code is how you implement it for the machine.

What is Pseudocode?

Pseudocode literally means ‘fake code’. It is an informal and contrived way of writing programs in which you represent the sequence of actions and instructions (aka algorithms) in a form that humans can easily understand.

You see, computers and human beings are quite different, and therein lies the problem.

The language of a computer is very rigid: you are not allowed to make any mistakes or deviate from the rules. Even with the invention of high-level, human-readable languages like JavaScript and Python, it’s still pretty hard for an average human developer to reason and program in those coding languages.

With pseudocode, however, it’s the exact opposite. You make the rules. It doesn’t matter what language you use to write your pseudocode. All that matters is comprehension.

In pseudocode, you don't have to think about semi-colons, curly braces, the syntax for arrow functions, how to define promises, DOM methods and other core language principles. You just have to be able to explain what you're thinking and doing.

Benefits of Writing Pseudocode

When you're writing code in a programming language, you’ll have to battle with strict syntax and rigid coding patterns. But you write pseudocode in a language or form with which you're very familiar.  

Since pseudocode is an informal method of program design, you don’t have to obey any set-out rules. You make the rules yourself.

Pseudocode acts as the bridge between your brain and computer’s code executor. It allows you to plan instructions which follow a logical pattern, without including all of the technical details.

Pseudocode is a great way of getting started with software programming as a beginner. You won’t have to overwhelm your brain with coding syntax.

In fact, many companies organize programming tests for their interviewees in pseudocode. This is because the importance of problem solving supersedes the ability to ‘hack’ computer code.

You can get quality code from many platforms online, but you have to learn problem solving and practice it a lot.

Planning computer algorithms with pseudocode makes you meticulous. It helps you explain exactly what each line in a software program should do. This is possible because you are in full control of everything, which is one of the great features of pseudocode.

Example of Pseudocode

Pseudocode is a very intuitive way to develop software programs. To illustrate this, I am going to refer back to a very simple program I wrote in my last article :

When a user fills in a form and clicks the submit button, execute a ValidateEmail function. What should the function do?

Once you are done outlining the various steps you want your code to take, everything becomes easier and clearer. Now, let’s turn that psedocode into real JavaScript code:

All you have to do at this stage is find the programming language constructs that will help you achieve each of your steps. Noticed how seamless the transition from pseudocode to actual code became? That’s how effective writing pseudocode can be for program design.

Pseudocode is also a great way to solve programming-related problems when you're struggling with them. For those practising programming in coding challenge platforms like CodeWars , pseudocode can be of immense help.

How to Solve Programming Problems with Pseudocode

Solving programming problems can be hard. Not only do you have the logical part to reckon with, but also the technical (code forming) part as well. I recently uncovered a brilliant and effective formula for solving tricky coding problems.

Here are the steps you can follow to solving programming problems with pseudocode:

Step 1: Understand what the function does

First, you need to understand that all a function does is (optionally) accept data as input, work on the data little by little, and finally return an output. The body of the function is what actually solves the problem and it does so line by line.

Step 2: Make sure you understand the question

Next, you need to read and understand the question properly. This is arguably the most important step in the process.

If you fail to properly understand the question, you won’t be able to work through the problem and figure out the possible steps to take. Once you identify the main problem to be solved you'll be ready to tackle it.

Step 3: Break the problem down.

Now you need to break down the problem into smaller parts and sub-problems. With each smaller problem you solve, you'll get closer to solving the main problem.

It helps to represent these problem solving steps in the clearest and most easily understandable way you can – which is psedocode!

I picked up this highly effective formula from Aaron Jack and I think you’ll benefit from it. Check out his video about how to solve coding problems:

As you can see, pseudocode is a very useful strategy for planning computer programs.

Of course, you have to remember that pseudocode is not a true representation of a computer program. While using pseudocode to plan your algorithm is great, you will ultimately have to translate it into an actual computer-readable program. This means that you'll eventually need to learn how to program in a real programming language.

Taking up coding challenges online is a great way to learn how to program because, as they say, practice makes perfect. But when you try your next challenge, don’t forget to implement pseudocode in the process!

You can check out some of my other programming-related posts on my personal blog . I am also available on Twitter .

Thank you for reading and see you soon.

P/S: If you are learning JavaScript, I created an eBook which teaches 50 topics in JavaScript with hand-drawn digital notes. Check it out here .

Helping you learn how to code one tutorial at a time. Online creator and entrepreneur.

If you read this far, tweet to the author to show them you care. Tweet a thanks

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

DEV Community

DEV Community

Cover image for How To Solve Algorithm And Data Structure Problems [Tips]

Posted on Sep 10, 2020 • Updated on Nov 29, 2020

How To Solve Algorithm And Data Structure Problems [Tips]

Are you struggling to solve coding problems? I’d like to share my own method to approach the solution. This is a reference on which I can build your own.

Table of Content

A. 5 Steps To Solve A Problem

1. Comprehend problem

2. Analyze Test Cases/Examples

3. Define Data Structure

4. Design Algorithm

williamfiset / Algorithms

A collection of algorithms and data structures.

5. Implement Algorithm

Given an array A of integers of size n . Commute the maxim sum of s contiguous elements in the array. Return -1 if there is no valid output.

1. Comprehend Problem

Information extraction:

When you read the problem carefully, you can extract crucial information and make it explicit to solve the problem. If you don’t highlight out important terms, you will not be able to come to the correct output, which is time-consuming. For example, if you miss “contiguous” (consecutive), you will try to find a maximum combination from a set of combinations of the array, which is absolutely wrong.

However, sometimes you face strange terminology which the problem’s author uses to describe the problem, I recommend you check out the list of common terms, List of terms relating to algorithms and data structures

You utilize the above information extraction to apply on the input and return the correct output, so that you evaluate your understanding on the given problem. After that, you should try to think beyond on the given examples for edge cases. Edge cases are unexpected inputs which drive your algorithm to be incorrect.

In this problem, you can directly use the given array as a representation of data. In other problems, you should think of all possible data structures, list them out on paper, and choose the most efficient one. For example, if you want to map one item to another item (key-value relationship), a hash table is the best choice.

To make the game start easily, you can come up with a brute-force solution, which is the inefficient algorithm. Then you try to optimize it by thinking beyond it. You use and modify techniques or good algorithms to fit your certain problem. Therefore, reading articles, books and other codes is useful to improve your knowledge of algorithms.

In this example, I would solve it in the brute-force way, and then optimize it with a technique called “Window Sliding”.

The above solution, you need to use one loop and one inner loop to iterate through s elements to find the maximum sum. It takes O(ns) times to gain the correct output. But can we eliminate s to reduce only O(n) . That’s where the “Window Sliding” technique comes to our playground.

Window Sliding is a technique of using a “window” with a specific length and run operation in this window. More specifically, consider a sub-array of length s, and move the sub-array by one element. Following the below figures to understand more:

Iteration 1

Here’s is a C# implementation of the above algorithm:

I hope that my step-by-step instructions can help you to form your own method of solving future problems. Remember, here is only a tip of solving a problem, and it does not try to show this is the only technique you should use to cope with any problem. Therefore, the more important tip I want to give you is PRACTICE, PRACTICE, AND PRACTICE .

If you find any mistakes in my post, you can comment below to correct me. Thanks for reading.

Top comments (0)

pic

Templates let you quickly answer FAQs or store snippets for re-use.

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink .

Hide child comments as well

For further actions, you may consider blocking this person and/or reporting abuse

🌚 Friends don't let friends browse without dark mode .

Sorry, it's true.

crutchcorn profile image

What Happened to UUIDv2?

Corbin Crutchley - Jan 16

theskilledcoder profile image

Hands-On Experience with Data Structures and Algorithms: 10 Project Ideas

Skilled Coder - Jan 16

vipert profile image

UraniumJS ☢️ - LZ4-compress & BASE92-encode ✔️

ViperT - Jan 5

harshrajpal profile image

57. Insert Interval

Harsh Rajpal - Jan 16

Once suspended, namvnngu will not be able to comment or publish posts until their suspension is removed.

Once unsuspended, namvnngu will be able to comment and publish posts again.

Once unpublished, all posts by namvnngu will become hidden and only accessible to themselves.

If namvnngu is not suspended, they can still re-publish their posts from their dashboard.

Once unpublished, this post will become invisible to the public and only accessible to Nam Nguyen.

They can still re-publish the post if they are not suspended.

Thanks for keeping DEV Community safe. Here is what you can do to flag namvnngu:

namvnngu consistently posts content that violates DEV Community's code of conduct because it is harassing, offensive or spammy.

Unflagging namvnngu will restore default visibility to their posts.

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Use the standard subtraction algorithm to solve the problems below

multiple times in any place using the standard subtraction algorithm, and apply the algorithm to solve word problems using tape diagrams.

Explain math problems

Homework Help Online

Clarify mathematic equation

Get the best Homework answer

Decide math problems

What Is Standard Algorithm Subtraction?

Standard algorithm subtraction is a 'formal' written method for solving questions and problems involving subtraction found within common core state

Math can be tough, but with a little practice, anyone can master it!

Reach support from expert tutors anytime, anywhere with Tutor.com.

Know is an AI-powered content marketing platform that makes it easy for businesses to create and distribute high-quality content.

Mathematics is a subject that can be very rewarding, both intellectually and personally.

Students said

My teacher wants me to simplify and graph and math app just does it for you. Can definitely be used just to copy answers but i've found it incredibly useful. I'm in the 8th Grade and since math is so damn confusing to me, I found this app.
It's really cool, if you're someone related to maths (student, scientist, engineer) you can't go on without this app, great free calculator 10/10 would recommend there are ads but there nothing horrible every 5 or 6 equations you see a ad. This app allowes me to get the answers and add the work later.
It is the one of the best app for math competitor. Best app ever, yeah I understand that it doesn't do like 10-20% of the math you put in but the 80-90% it does do it gives the correct answer. This app is great in solving problems. Its impressive when it reads and solves a wrote out question.

Addition & Subtraction to 1,000 using standard algorithm

Using blocks, the subtraction problem is shown below: The traditional, standard subtraction algorithm is not necessarily the best one

IMAGES

  1. Genetic Algorithms in Elixir: Solve Problems Using Evolution

    how to solve problems using algorithms

  2. Why Using Algorithms to Solve Everyday Problems is the Future

    how to solve problems using algorithms

  3. 😂 Algorithmic problem solving. Algorithmic Problem Solving Free Pdf Download. 2019-03-06

    how to solve problems using algorithms

  4. Meta algorithm for problem solving Other interesting observation on...

    how to solve problems using algorithms

  5. Problem-solving algorithm

    how to solve problems using algorithms

  6. How Algorithms Are Used in Problem Solving in Pyschology

    how to solve problems using algorithms

VIDEO

  1. Common algorithms you should know

  2. Percentage bar diagram |Statistics

  3. solve a algorithm

  4. best algorithm that solve your 2x2 in 1 sec!

  5. What is an Algorithm 1

  6. What algorithm do u use to solve this

COMMENTS

  1. How to use algorithms to solve everyday problems

    Algorithmic thinking is taking a step back and asking, "If it's the case that algorithms are so useful in computing to achieve predictability, might they also be useful in everyday life, when it comes to, say, deciding between alternative ways of solving a problem or completing a task?"

  2. Algorithms

    Learn merge sort, a more efficient sorting algorithm that relies heavily on the power of recursion to repeatedly sort and merge sub-arrays. Learn Divide and conquer algorithms Overview of merge sort Challenge: Implement merge sort Linear-time merging Challenge: Implement merge Analysis of merge sort Quick sort

  3. How to Use Algorithms to Solve Problems?

    Let's take some examples of algorithms for computer science problems. Example 1. Swap two numbers with a third variable Step 1: Start Step 2: Take 2 numbers as input. Step 3: Declare another variable as "temp". Step 4: Store the first variable to "temp". Step 5: Store the second variable to the First variable.

  4. Heuristics & approximate solutions

    Heuristics like "local search" help narrow down the array of possible locations. 20 locations and a possible solution with 5 facilities. All of these are combinatorial problems, where a computer would need to search an exponentially growing number of combinations to find the optimal answer.

  5. How to Solve Problems Using Algorithms

    An algorithm is a set of instructions or steps that can be followed to solve a specific problem or task. Algorithms are essential building blocks of software engineering, machine learning and ...

  6. What is Algorithm

    1.Algorithms are necessary for solving complex problems efficiently and effectively. 2.They help to automate processes and make them more reliable, faster, and easier to perform. 3.Algorithms also enable computers to perform tasks that would be difficult or impossible for humans to do manually.

  7. How to Think Algorithmically: 12 Steps

    Practice your algorithmic thinking by solving your daily tasks as if they're algorithms. Plan out logical steps and use the if-then approach to accomplish them. Over time, you'll get used to solving problems this way. [10] A recipe, for example, is essentially an algorithm.

  8. Solve Algorithms

    Algorithms. Algorithms. Solve Me First. Easy Problem Solving (Basic) Max Score: 1 Success Rate: 98.17%. Solve Challenge. ... Easy Problem Solving (Basic) Max Score: 10 Success Rate: 97.04%. Solve Challenge. Time Conversion. Easy Problem Solving (Basic) Max Score: 15 Success Rate: 92.03%. Solve Challenge. Status.

  9. How to Solve Tough Problems Using Genetic Algorithms

    There are 2 prerequisites that makes our problem eligible for using genetic algorithms: 1. We need to understand how to represent a solution to the problem. 2. We should have the ability to calculate continuous fitness. If our problem meets these criteria, we're good to go.

  10. How To Problem-Solve With An Algorithm: Psychology And ...

    The step-by-step instructions which inherently comprise algorithms are what helps people solve problems. In a nutshell, an algorithm is a formula which is designed to reach a solution. Some algorithms are complicated, while others are simple and fairly easy to get an understanding of.

  11. The Algorithm Problem Solving Approach in Psychology

    There are situations where using an algorithm can be the best approach: When accuracy is crucial: This is useful in situations when accuracy is critical or where similar problems need to be frequently solved. 2 In many cases, computer programs can be designed to speed up this process.

  12. Steps to Algorithmic Problem-Solving in Examples

    Following the steps of an algorithm should be consistent despite problems changing. For example, in the multiplication problem {eq}83 \cdot 72 {/eq}, the Partial Products algorithm can be...

  13. An Introduction to Problem-Solving using Search Algorithms for Beginners

    The process of problem-solving using searching consists of the following steps. Define the problem Analyze the problem Identification of possible solutions Choosing the optimal solution Implementation Let's discuss some of the essential properties of search algorithms. Properties of search algorithms Completeness

  14. Top 10 machine learning algorithms with their use-cases

    Decision Trees. Decision Trees are one of the most popular machine-learning algorithms. They are used for classification, regression, and anomaly detection. Decision trees set up a hierarchy of ...

  15. Problem Solving Using Data Structures and Algorithms

    How to solve coding problems using Data Structures and Algorithms. This is an overview lecture of the course that follows. This is Part 1 of this series.

  16. Dynamic Programming

    3.3M views 2 years ago Learn how to use Dynamic Programming in this course for beginners. It can help you solve complex programming problems, such as those often seen in programming interview...

  17. solving_problems_algorithms_worksheet.docx

    Solving Problems with Algorithms Worksheet Part 1: Write Algorithm Create an algorithm using pseudocode that someone else can follow. Choose one of the following options: How to make a grilled cheese sandwich How to do a load of laundry How to tie a shoe My Algorithm for: How to download mobile games when your PC isn't compatible with Google Play.

  18. 8.2 Problem-Solving: Heuristics and Algorithms

    Algorithms. In contrast to heuristics, which can be thought of as problem-solving strategies based on educated guesses, algorithms are problem-solving strategies that use rules. Algorithms are generally a logical set of steps that, if applied correctly, should be accurate. For example, you could make a cake using heuristics — relying on your ...

  19. Top 20 Algorithms Problems for Coding Interviews with Solutions

    Top 20 Algorithms Coding Problems for Programming Interviews with Solutions | by javinpaul | Javarevisited | Medium 500 Apologies, but something went wrong on our end. Refresh the page, check...

  20. The Key to Solving Business Problems: Algorithms

    Problems are handled with algorithms, and important solutions are created. There are many ways that the flexon approach improves upon the traditional way of solving problems. In the work environment, flexons actually enhance the concept of experience in an employee by quantifying the past experiences that shape a person's actions in the future.

  21. An algorithm for split equilibrium and fixed-point problems using

    We study in this article, split equilibrium fixed-point problems involving pseudomonotone bifunctions which satisfy Lipschitz-type continuous condition and nonexpansive mappings, respectively, in real Hilbert spaces. In order to solve this problem, we propose an inertial extragradient algorithm and establish strong convergence theorem using the sequence of the algorithm under mild conditions ...

  22. Steps of Problem Solving in Data Structures and Algorithms

    Step 3: Designing efficient pseudocode solutions. This is a stage to use the best experience of problem-solving and apply various problem-solving strategies. One practical truth is: moving from a basic algorithm to the most efficient algorithm is a little difficult in a single step. Each time, we need to optimize the previous algorithm and stop ...

  23. rushingfox/Evolutionary-Algorithm-to-solve-the-Inverse-Problem-of

    For two types of Differential Equations: ellipse and parabola; Not only reproduced the old algorithm but also proposed a new step-wise algorithm to fix two weaknesses of the old algorithm - GitHub - rushingfox/Evolutionary-Algorithm-to-solve-the-Inverse-Problem-of-Differential-Equations: For two types of Differential Equations: ellipse and parabola; Not only reproduced the old algorithm but ...

  24. What is Pseudocode? How to Use Pseudocode to Solve Coding Problems

    Once you identify the main problem to be solved you'll be ready to tackle it. Step 3: Break the problem down. Now you need to break down the problem into smaller parts and sub-problems. With each smaller problem you solve, you'll get closer to solving the main problem. It helps to represent these problem solving steps in the clearest and most ...

  25. How To Solve Algorithm And Data Structure Problems [Tips]

    A. 5 Steps To Solve A Problem. 1. Comprehend problem. Read the problem carefully (and underline keywords) Extract rules from problem. 2. Analyze Test Cases/Examples. Identify and evaluate Input/Output. Understand how the output is produced for each input.

  26. Use the standard subtraction algorithm to solve the problems below

    Directions: Use the standard subtraction algorithm to solve the problems below. Clarify math questions. If you need help, we're here for you 24/7. Do homework. The best way to protect your data is to keep it secure. Guaranteed Originality. The best way to download full math explanation, it's download answer here. ...