How to Solve an Algorithm Problem? | With Examples

developer team coding javascript

If you’re stuck on an algorithm problem and not sure how to proceed, this blog post is for you! We’ll go over some general tips on solving algorithm problems, as well as a specific example of an algorithm .

Table of content:

Introduction.

  • What are the 4 steps of algorithmic problem solving?
  • Conclusion and References

[365 Toy Project: 022/365] Batman: Scarlet Part 4 - Solve the problem - Solve an Algorithm.

What is an Algorithm?

What is an algorithm? Put simply, an algorithm is a step-by-step procedure for solving a problem. Algorithms can be written in any programming language, but they all share some common characteristics. First and foremost, algorithms are sequence tasks . That means that the steps in the algorithm must be done in order, and each step depends on the results of the previous steps. Secondly, algorithms are deterministic: given the same input data, exactly the same program will produce the same output every time. Finally, there are some measures for an algorithm to be efficient. Time and space: those two measures determine how efficient your algorithm is.

Computer geometric digital connection structure. Business inteligence technology background. Wirefra

How to Solve an Algorithm Problem?

We’ll walk through some steps for solving a particular algorithm .

First, it’s important to know the basics of algorithms: every problem can be broken down into a sequence of steps that can be solved. This is known as the analysis of algorithms . Sketch out the basic structure of your algorithm on paper first or a board to avoid confusion. write some thoughts about which does what.

If a problem involves mathematical operations, conceptualizing it in terms of equations may be helpful. Break down the equation into its component parts and see if any of those particular pieces can be simplified or eliminated altogether. If so, that will lead to a solution for the whole equation.

Another strategy is to try reversing what initially seems like an impossible task. Algorithms problems often have stages were doing something one-way results in an error message or produces no useful output at all. Reverse engineer those steps and see if anything productive comes out.

What are the 4 steps of algorithmic problem-solving? and Example #1

Now that you know what an algorithm is, let’s jump into some examples and take a look at how these techniques can be put into practice…

In the following we will use the problem challenge from leetcode number #387 :

1) Understand the problem

The goal of any algorithm is to solve a problem.  When solving an algorithm problem, it is important to understand the problem and the steps involved in solving it. This understanding will allow you to correctly follow the instructions and complete the task. Answer the common questions to be sure that you really understand the problem. Questions like what it does and what kind of input I’m expecting. what kind of output I should receive? Are there some exceptions I should be aware of? etc…

The goal of this challenge is to write a function that takes in a string and returns the index of the first letter in the string that does not repeat. For example, if the string is “nerd”, the function should return 0, because the first letter “n” is the first non-repeating letter in the string. If the string is “abcdefg”, the function should return 0, because the first letter “a” is the first non-repeating letter in the string.

If the string does not contain any non-repeating letters, the function should return -1. For example, if the input string is “abcabc”, the function should return -1, because no letter in the string is unique or non-repeating.

2) Break the problem down

When solving algorithms problems , breaking them down into smaller parts is usually the best way to go. Once you understand how each part works and interacts with the others, you can solve the problem more quickly.

To solve this challenge, we need to do the following:

  • Iterate over the letters in the input string, and for each letter, keep track of how many times it appears in the string. We can do this using an object, dictionary, or map, where the keys are the letters in the string, and the values are the counts for each letter.
  • Once we have counted the occurrences of each letter in the string, we need to find the index of the first letter that has a count of 1 (i.e. the first non-repeating letter). To do this, we can iterate over the letters in the string again, and for each letter, check if its count in the object/dictionary is 1. If it is, we return the index of the letter.
  • If we reach the end of the loop without finding any value that has only 1 or non-repeating letters, we return -1 to indicate that no non-repeating letters were found.

3) Find your solution

We found one solution and the key steps in this solution are to keep track of the counts of each letter in the input string, and then to search for the first letter with a count of 1.  If the count of this letter is 1 meaning that this letter only shows one time in the string. These steps can be implemented in a variety of ways, depending on the language and tools you are using to solve the challenge.

We will be demonstrating the solution with two programming languages JavaScript and Python:

The source code in JavaScript:

Here are some examples of how this function can be used:

The source code in Python :

4) Check your solution

Checking your solution again answers some questions like can I write a better code? by better I mean is the code I provided covering all cases of inputs? is it efficient? and by efficient, I mean using fewer computer resources when possible. If you’re comfortable with your answers then check if there is another solution out there for the same problem you solved, if any are found. go through them I learned a lot by doing that. Also get some feedback on your code, that way you’ll learn many ways of approaching a problem to solve it.

As we mentioned above we asked ourselves these questions but the algorithm we wrote couldn’t go through all the different cases successfully: for example, The code can’t handle the case when we handled two cases of the same character “L” and “l” in the word “Level”

So we need to address that in the following:

Now let’s revisit the code that we wrote up and see if we can come up with another solution that will cover the all different cases of a character.

The source code in JavaScript :

Now that you learned from the first example, let’s jump into another challenge and apply the same techniques we used above:

This example from leetcode problem #125 Valid Palindrome

Learn as much information as you can about the problem what is a Palindrome? Ask yourself what input you expect and what output is expected.

The Palindrome is a word, phrase, or sentence that is spelled backward as forwards. We expect a string and we can do a function that first cleans that string from any non-alphanumeric, then reverses it and compares it with the original string.

Here is a step-by-step explanation of the algorithm in plain English:

  • Convert all uppercase letters in the string to lowercase. This is done so that the case of the letters in the string does not affect the outcome of the comparison.
  • Remove all non-alphanumeric characters from the string. This is done because only alphanumeric characters are relevant for determining if a string is a palindrome.
  • Reverse the resulting string. This is done so that we can compare the reversed string with the original string.
  • Compare the reversed string with the original string. If they are the same, then the original string is a palindrome. Otherwise, it is not.

Here is an example of how this algorithm would work on the string “A man, a plan, a canal: Panama”:

  • The string is converted to lowercase, so it becomes “a man, a plan, a canal: panama”.
  • All non-alphanumeric characters are removed, so the string becomes “amanaplanacanalpanama”.
  • The string is reversed, so it becomes “amanaplanacanalpanama”.
  • The reversed string is compared with the original string, and since they are the same, the function returns true, indicating that the original string is a palindrome.

According to the steps we wrote in the previous stage, let’s put them into action and code it up.

The source code in Python:

We can make it more efficient by using the pointers method let’s break it down into a few points below:

  • Create left and right pointers (will be represented by indices)
  • Make each pointer move to the middle direction
  • While moving to check each letter for both pointers are the same

Quantum computer technology concept. Deep learning artificial intelligence. Big data algorithms visu

Conclusion and references

There are many resources available to help you out, and with more practice , you’ll be able to solve many algorithm problems that come your way . This video is one of the great resources to learn about algorithms and data structures from FreeCodeCamp

It is important to keep a cool head and not get bogged down in frustration. Algorithms problems can be difficult, but with patience and perseverance, they can be solved.

When you are solving an algorithm problem, it is important to be able to check your solution against other solutions if possible to see how others approach the same problem. This is will help you to retain and understand the logic behind the different solutions so you’ll need this kind of knowledge in the future solving problems.

By following the steps outlined in this article, you will be able to solve algorithm problems with ease. Remember to keep a notebook or excel sheet with all of your solutions so that you can revisit them later on that way you will gain maximum retention of the logic.

If you want to learn more about algorithms and programming , sign up for our mailing list. We’ll send you tips, tricks, and resources to help you improve your skills.

example problem solving algorithms

Ahmed Radwan

Reach out if you want to join me and write articles with the nerds 🙂

How to Make Your Corporate Website Stand Out With These 10 Tips

How to write clean code and best practices, you may also like, javascript: resolved and rejected promises, here are some new features in javascript, top 100 problems on leetcode and its solutions – part1.

  • Smart Devices
  • Programming
  • Web Development
  • Presentation
  • Infographics

Smart. Open. Grounded. Inventive. Read our Ideas Made to Matter.

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.

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

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.

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.

Apply now and work for two to five years. We'll save you a seat in our MBA class when you're ready to come back to campus for your degree.

Executive Programs

The 20-month program teaches the science of management to mid-career leaders who want to move from success to significance.

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

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

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

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

This finance exec is a fan of nonlinear career paths

Wealthier workers benefit most from retirement savings ‘nudges’

The risk of letting junior professionals teach AI to senior colleagues

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

Cars and trucks on the highway with AI/digital graphics overlayed on top

  • 1. Micro-Worlds
  • 2. Light-Bot in Java
  • 3. Jeroos of Santong Island
  • 4. Problem Solving and Algorithms
  • 5. Creating Jeroo Methods
  • 6. Conditionally Executing Actions
  • 7. Repeating Actions
  • 8. Handling Touch Events
  • 9. Adding Text to the Screen

Problem Solving and Algorithms

Learn a basic process for developing a solution to a problem. Nothing in this chapter is unique to using a computer to solve a problem. This process can be used to solve a wide variety of problems, including ones that have nothing to do with computers.

Problems, Solutions, and Tools

I have a problem! I need to thank Aunt Kay for the birthday present she sent me. I could send a thank you note through the mail. I could call her on the telephone. I could send her an email message. I could drive to her house and thank her in person. In fact, there are many ways I could thank her, but that's not the point. The point is that I must decide how I want to solve the problem, and use the appropriate tool to implement (carry out) my plan. The postal service, the telephone, the internet, and my automobile are tools that I can use, but none of these actually solves my problem. In a similar way, a computer does not solve problems, it's just a tool that I can use to implement my plan for solving the problem.

Knowing that Aunt Kay appreciates creative and unusual things, I have decided to hire a singing messenger to deliver my thanks. In this context, the messenger is a tool, but one that needs instructions from me. I have to tell the messenger where Aunt Kay lives, what time I would like the message to be delivered, and what lyrics I want sung. A computer program is similar to my instructions to the messenger.

The story of Aunt Kay uses a familiar context to set the stage for a useful point of view concerning computers and computer programs. The following list summarizes the key aspects of this point of view.

A computer is a tool that can be used to implement a plan for solving a problem.

A computer program is a set of instructions for a computer. These instructions describe the steps that the computer must follow to implement a plan.

An algorithm is a plan for solving a problem.

A person must design an algorithm.

A person must translate an algorithm into a computer program.

This point of view sets the stage for a process that we will use to develop solutions to Jeroo problems. The basic process is important because it can be used to solve a wide variety of problems, including ones where the solution will be written in some other programming language.

An Algorithm Development Process

Every problem solution starts with a plan. That plan is called an algorithm.

There are many ways to write an algorithm. Some are very informal, some are quite formal and mathematical in nature, and some are quite graphical. The instructions for connecting a DVD player to a television are an algorithm. A mathematical formula such as πR 2 is a special case of an algorithm. The form is not particularly important as long as it provides a good way to describe and check the logic of the plan.

The development of an algorithm (a plan) is a key step in solving a problem. Once we have an algorithm, we can translate it into a computer program in some programming language. Our algorithm development process consists of five major steps.

Step 1: Obtain a description of the problem.

Step 2: analyze the problem., step 3: develop a high-level algorithm., step 4: refine the algorithm by adding more detail., step 5: review the algorithm..

This step is much more difficult than it appears. In the following discussion, the word client refers to someone who wants to find a solution to a problem, and the word developer refers to someone who finds a way to solve the problem. The developer must create an algorithm that will solve the client's problem.

The client is responsible for creating a description of the problem, but this is often the weakest part of the process. It's quite common for a problem description to suffer from one or more of the following types of defects: (1) the description relies on unstated assumptions, (2) the description is ambiguous, (3) the description is incomplete, or (4) the description has internal contradictions. These defects are seldom due to carelessness by the client. Instead, they are due to the fact that natural languages (English, French, Korean, etc.) are rather imprecise. Part of the developer's responsibility is to identify defects in the description of a problem, and to work with the client to remedy those defects.

The purpose of this step is to determine both the starting and ending points for solving the problem. This process is analogous to a mathematician determining what is given and what must be proven. A good problem description makes it easier to perform this step.

When determining the starting point, we should start by seeking answers to the following questions:

What data are available?

Where is that data?

What formulas pertain to the problem?

What rules exist for working with the data?

What relationships exist among the data values?

When determining the ending point, we need to describe the characteristics of a solution. In other words, how will we know when we're done? Asking the following questions often helps to determine the ending point.

What new facts will we have?

What items will have changed?

What changes will have been made to those items?

What things will no longer exist?

An algorithm is a plan for solving a problem, but plans come in several levels of detail. It's usually better to start with a high-level algorithm that includes the major part of a solution, but leaves the details until later. We can use an everyday example to demonstrate a high-level algorithm.

Problem: I need a send a birthday card to my brother, Mark.

Analysis: I don't have a card. I prefer to buy a card rather than make one myself.

High-level algorithm:

Go to a store that sells greeting cards Select a card Purchase a card Mail the card

This algorithm is satisfactory for daily use, but it lacks details that would have to be added were a computer to carry out the solution. These details include answers to questions such as the following.

"Which store will I visit?"

"How will I get there: walk, drive, ride my bicycle, take the bus?"

"What kind of card does Mark like: humorous, sentimental, risqué?"

These kinds of details are considered in the next step of our process.

A high-level algorithm shows the major steps that need to be followed to solve a problem. Now we need to add details to these steps, but how much detail should we add? Unfortunately, the answer to this question depends on the situation. We have to consider who (or what) is going to implement the algorithm and how much that person (or thing) already knows how to do. If someone is going to purchase Mark's birthday card on my behalf, my instructions have to be adapted to whether or not that person is familiar with the stores in the community and how well the purchaser known my brother's taste in greeting cards.

When our goal is to develop algorithms that will lead to computer programs, we need to consider the capabilities of the computer and provide enough detail so that someone else could use our algorithm to write a computer program that follows the steps in our algorithm. As with the birthday card problem, we need to adjust the level of detail to match the ability of the programmer. When in doubt, or when you are learning, it is better to have too much detail than to have too little.

Most of our examples will move from a high-level to a detailed algorithm in a single step, but this is not always reasonable. For larger, more complex problems, it is common to go through this process several times, developing intermediate level algorithms as we go. Each time, we add more detail to the previous algorithm, stopping when we see no benefit to further refinement. This technique of gradually working from a high-level to a detailed algorithm is often called stepwise refinement .

The final step is to review the algorithm. What are we looking for? First, we need to work through the algorithm step by step to determine whether or not it will solve the original problem. Once we are satisfied that the algorithm does provide a solution to the problem, we start to look for other things. The following questions are typical of ones that should be asked whenever we review an algorithm. Asking these questions and seeking their answers is a good way to develop skills that can be applied to the next problem.

Does this algorithm solve a very specific problem or does it solve a more general problem ? If it solves a very specific problem, should it be generalized?

For example, an algorithm that computes the area of a circle having radius 5.2 meters (formula π*5.2 2 ) solves a very specific problem, but an algorithm that computes the area of any circle (formula π*R 2 ) solves a more general problem.

Can this algorithm be simplified ?

One formula for computing the perimeter of a rectangle is:

length + width + length + width

A simpler formula would be:

2.0 * ( length + width )

Is this solution similar to the solution to another problem? How are they alike? How are they different?

For example, consider the following two formulae:

Rectangle area = length * width Triangle area = 0.5 * base * height

Similarities: Each computes an area. Each multiplies two measurements.

Differences: Different measurements are used. The triangle formula contains 0.5.

Hypothesis: Perhaps every area formula involves multiplying two measurements.

Example 4.1: Pick and Plant

This section contains an extended example that demonstrates the algorithm development process. To complete the algorithm, we need to know that every Jeroo can hop forward, turn left and right, pick a flower from its current location, and plant a flower at its current location.

Problem Statement (Step 1)

A Jeroo starts at (0, 0) facing East with no flowers in its pouch. There is a flower at location (3, 0). Write a program that directs the Jeroo to pick the flower and plant it at location (3, 2). After planting the flower, the Jeroo should hop one space East and stop. There are no other nets, flowers, or Jeroos on the island.

StartFinish

Analysis of the Problem (Step 2)

The flower is exactly three spaces ahead of the jeroo.

The flower is to be planted exactly two spaces South of its current location.

The Jeroo is to finish facing East one space East of the planted flower.

There are no nets to worry about.

High-level Algorithm (Step 3)

Let's name the Jeroo Bobby. Bobby should do the following:

Get the flower Put the flower Hop East

Detailed Algorithm (Step 4)

Get the flower Hop 3 times Pick the flower Put the flower Turn right Hop 2 times Plant a flower Hop East Turn left Hop once

Review the Algorithm (Step 5)

The high-level algorithm partitioned the problem into three rather easy subproblems. This seems like a good technique.

This algorithm solves a very specific problem because the Jeroo and the flower are in very specific locations.

This algorithm is actually a solution to a slightly more general problem in which the Jeroo starts anywhere, and the flower is 3 spaces directly ahead of the Jeroo.

Java Code for "Pick and Plant"

A good programmer doesn't write a program all at once. Instead, the programmer will write and test the program in a series of builds. Each build adds to the previous one. The high-level algorithm will guide us in this process.

FIRST BUILD

To see this solution in action, create a new Greenfoot4Sofia scenario and use the Edit Palettes Jeroo menu command to make the Jeroo classes visible. Right-click on the Island class and create a new subclass with the name of your choice. This subclass will hold your new code.

The recommended first build contains three things:

The main method (here myProgram() in your island subclass).

Declaration and instantiation of every Jeroo that will be used.

The high-level algorithm in the form of comments.

The instantiation at the beginning of myProgram() places bobby at (0, 0), facing East, with no flowers.

Once the first build is working correctly, we can proceed to the others. In this case, each build will correspond to one step in the high-level algorithm. It may seem like a lot of work to use four builds for such a simple program, but doing so helps establish habits that will become invaluable as the programs become more complex.

SECOND BUILD

This build adds the logic to "get the flower", which in the detailed algorithm (step 4 above) consists of hopping 3 times and then picking the flower. The new code is indicated by comments that wouldn't appear in the original (they are just here to call attention to the additions). The blank lines help show the organization of the logic.

By taking a moment to run the work so far, you can confirm whether or not this step in the planned algorithm works as expected.

THIRD BUILD

This build adds the logic to "put the flower". New code is indicated by the comments that are provided here to mark the additions.

FOURTH BUILD (final)

Example 4.2: replace net with flower.

This section contains a second example that demonstrates the algorithm development process.

There are two Jeroos. One Jeroo starts at (0, 0) facing North with one flower in its pouch. The second starts at (0, 2) facing East with one flower in its pouch. There is a net at location (3, 2). Write a program that directs the first Jeroo to give its flower to the second one. After receiving the flower, the second Jeroo must disable the net, and plant a flower in its place. After planting the flower, the Jeroo must turn and face South. There are no other nets, flowers, or Jeroos on the island.

Jeroo_2 is exactly two spaces behind Jeroo_1.

The only net is exactly three spaces ahead of Jeroo_2.

Each Jeroo has exactly one flower.

Jeroo_2 will have two flowers after receiving one from Jeroo_1. One flower must be used to disable the net. The other flower must be planted at the location of the net, i.e. (3, 2).

Jeroo_1 will finish at (0, 1) facing South.

Jeroo_2 is to finish at (3, 2) facing South.

Each Jeroo will finish with 0 flowers in its pouch. One flower was used to disable the net, and the other was planted.

Let's name the first Jeroo Ann and the second one Andy.

Ann should do the following: Find Andy (but don't collide with him) Give a flower to Andy (he will be straight ahead) After receiving the flower, Andy should do the following: Find the net (but don't hop onto it) Disable the net Plant a flower at the location of the net Face South
Ann should do the following: Find Andy Turn around (either left or right twice) Hop (to location (0, 1)) Give a flower to Andy Give ahead Now Andy should do the following: Find the net Hop twice (to location (2, 2)) Disable the net Toss Plant a flower at the location of the net Hop (to location (3, 2)) Plant a flower Face South Turn right

The high-level algorithm helps manage the details.

This algorithm solves a very specific problem, but the specific locations are not important. The only thing that is important is the starting location of the Jeroos relative to one another and the location of the net relative to the second Jeroo's location and direction.

Java Code for "Replace Net with Flower"

As before, the code should be written incrementally as a series of builds. Four builds will be suitable for this problem. As usual, the first build will contain the main method, the declaration and instantiation of the Jeroo objects, and the high-level algorithm in the form of comments. The second build will have Ann give her flower to Andy. The third build will have Andy locate and disable the net. In the final build, Andy will place the flower and turn East.

This build creates the main method, instantiates the Jeroos, and outlines the high-level algorithm. In this example, the main method would be myProgram() contained within a subclass of Island .

This build adds the logic for Ann to locate Andy and give him a flower.

This build adds the logic for Andy to locate and disable the net.

This build adds the logic for Andy to place a flower at (3, 2) and turn South.

  • Part 2 Problem-solving »
  • Chapter 3 Solving Problems by Searching
  • Edit on GitHub

Chapter 3 Solving Problems by Searching 

When the correct action to take is not immediately obvious, an agent may need to plan ahead : to consider a sequence of actions that form a path to a goal state. Such an agent is called a problem-solving agent , and the computational process it undertakes is called search .

Problem-solving agents use atomic representations, that is, states of the world are considered as wholes, with no internal structure visible to the problem-solving algorithms. Agents that use factored or structured representations of states are called planning agents .

We distinguish between informed algorithms, in which the agent can estimate how far it is from the goal, and uninformed algorithms, where no such estimate is available.

3.1 Problem-Solving Agents 

If the agent has no additional information—that is, if the environment is unknown —then the agent can do no better than to execute one of the actions at random. For now, we assume that our agents always have access to information about the world. With that information, the agent can follow this four-phase problem-solving process:

GOAL FORMULATION : Goals organize behavior by limiting the objectives and hence the actions to be considered.

PROBLEM FORMULATION : The agent devises a description of the states and actions necessary to reach the goal—an abstract model of the relevant part of the world.

SEARCH : Before taking any action in the real world, the agent simulates sequences of actions in its model, searching until it finds a sequence of actions that reaches the goal. Such a sequence is called a solution .

EXECUTION : The agent can now execute the actions in the solution, one at a time.

It is an important property that in a fully observable, deterministic, known environment, the solution to any problem is a fixed sequence of actions . The open-loop system means that ignoring the percepts breaks the loop between agent and environment. If there is a chance that the model is incorrect, or the environment is nondeterministic, then the agent would be safer using a closed-loop approach that monitors the percepts.

In partially observable or nondeterministic environments, a solution would be a branching strategy that recommends different future actions depending on what percepts arrive.

3.1.1 Search problems and solutions 

A search problem can be defined formally as follows:

A set of possible states that the environment can be in. We call this the state space .

The initial state that the agent starts in.

A set of one or more goal states . We can account for all three of these possibilities by specifying an \(Is\-Goal\) method for a problem.

The actions available to the agent. Given a state \(s\) , \(Actions(s)\) returns a finite set of actions that can be executed in \(s\) . We say that each of these actions is applicable in \(s\) .

A transition model , which describes what each action does. \(Result(s,a)\) returns the state that results from doing action \(a\) in state \(s\) .

An action cost function , denote by \(Action\-Cost(s,a,s\pr)\) when we are programming or \(c(s,a,s\pr)\) when we are doing math, that gives the numeric cost of applying action \(a\) in state \(s\) to reach state \(s\pr\) .

A sequence of actions forms a path , and a solution is a path from the initial state to a goal state. We assume that action costs are additive; that is, the total cost of a path is the sum of the individual action costs. An optimal solution has the lowest path cost among all solutions.

The state space can be represented as a graph in which the vertices are states and the directed edges between them are actions.

3.1.2 Formulating problems 

The process of removing detail from a representation is called abstraction . The abstraction is valid if we can elaborate any abstract solution into a solution in the more detailed world. The abstraction is useful if carrying out each of the actions in the solution is easier than the original problem.

3.2 Example Problems 

A standardized problem is intended to illustrate or exercise various problem-solving methods. It can be given a concise, exact description and hence is suitable as a benchmark for researchers to compare the performance of algorithms. A real-world problem , such as robot navigation, is one whose solutions people actually use, and whose formulation is idiosyncratic, not standardized, because, for example, each robot has different sensors that produce different data.

3.2.1 Standardized problems 

A grid world problem is a two-dimensional rectangular array of square cells in which agents can move from cell to cell.

Vacuum world

Sokoban puzzle

Sliding-tile puzzle

3.2.2 Real-world problems 

Route-finding problem

Touring problems

Trveling salesperson problem (TSP)

VLSI layout problem

Robot navigation

Automatic assembly sequencing

3.3 Search Algorithms 

A search algorithm takes a search problem as input and returns a solution, or an indication of failure. We consider algorithms that superimpose a search tree over the state-space graph, forming various paths from the initial state, trying to find a path that reaches a goal state. Each node in the search tree corresponds to a state in the state space and the edges in the search tree correspond to actions. The root of the tree corresponds to the initial state of the problem.

The state space describes the (possibly infinite) set of states in the world, and the actions that allow transitions from one state to another. The search tree describes paths between these states, reaching towards the goal. The search tree may have multiple paths to (and thus multiple nodes for) any given state, but each node in the tree has a unique path back to the root (as in all trees).

The frontier separates two regions of the state-space graph: an interior region where every state has been expanded, and an exterior region of states that have not yet been reached.

3.3.1 Best-first search 

In best-first search we choose a node, \(n\) , with minimum value of some evaluation function , \(f(n)\) .

../_images/Fig3.7.png

3.3.2 Search data structures 

A node in the tree is represented by a data structure with four components

\(node.State\) : the state to which the node corresponds;

\(node.Parent\) : the node in the tree that generated this node;

\(node.Action\) : the action that was applied to the parent’s state to generate this node;

\(node.Path\-Cost\) : the total cost of the path from the initial state to this node. In mathematical formulas, we use \(g(node)\) as a synonym for \(Path\-Cost\) .

Following the \(PARENT\) pointers back from a node allows us to recover the states and actions along the path to that node. Doing this from a goal node gives us the solution.

We need a data structure to store the frontier . The appropriate choice is a queue of some kind, because the operations on a frontier are:

\(Is\-Empty(frontier)\) returns true only if there are no nodes in the frontier.

\(Pop(frontier)\) removes the top node from the frontier and returns it.

\(Top(frontier)\) returns (but does not remove) the top node of the frontier.

\(Add(node, frontier)\) inserts node into its proper place in the queue.

Three kinds of queues are used in search algorithms:

A priority queue first pops the node with the minimum cost according to some evaluation function, \(f\) . It is used in best-first search.

A FIFO queue or first-in-first-out queue first pops the node that was added to the queue first; we shall see it is used in breadth-first search.

A LIFO queue or last-in-first-out queue (also known as a stack ) pops first the most recently added node; we shall see it is used in depth-first search.

3.3.3 Redundant paths 

A cycle is a special case of a redundant path .

As the saying goes, algorithms that cannot remember the past are doomed to repeat it . There are three approaches to this issue.

First, we can remember all previously reached states (as best-first search does), allowing us to detect all redundant paths, and keep only the best path to each state.

Second, we can not worry about repeating the past. We call a search algorithm a graph search if it checks for redundant paths and a tree-like search if it does not check.

Third, we can compromise and check for cycles, but not for redundant paths in general.

3.3.4 Measuring problem-solving performance 

COMPLETENESS : Is the algorithm guaranteed to find a solution when there is one, and to correctly report failure when there is not?

COST OPTIMALITY : Does it find a solution with the lowest path cost of all solutions?

TIME COMPLEXITY : How long does it take to find a solution?

SPACE COMPLEXITY : How much memory is needed to perform the search?

To be complete, a search algorithm must be systematic in the way it explores an infinite state space, making sure it can eventually reach any state that is connected to the initial state.

In theoretical computer science, the typical measure of time and space complexity is the size of the state-space graph, \(|V|+|E|\) , where \(|V|\) is the number of vertices (state nodes) of the graph and \(|E|\) is the number of edges (distinct state/action pairs). For an implicit state space, complexity can be measured in terms of \(d\) , the depth or number of actions in an optimal solution; \(m\) , the maximum number of actions in any path; and \(b\) , the branching factor or number of successors of a node that need to be considered.

3.4 Uninformed Search Strategies 

3.4.1 breadth-first search .

When all actions have the same cost, an appropriate strategy is breadth-first search , in which the root node is expanded first, then all the successors of the root node are expanded next, then their successors, and so on.

../_images/Fig3.9.png

Breadth-first search always finds a solution with a minimal number of actions, because when it is generating nodes at depth \(d\) , it has already generated all the nodes at depth \(d-1\) , so if one of them were a solution, it would have been found.

All the nodes remain in memory, so both time and space complexity are \(O(b^d)\) . The memory requirements are a bigger problem for breadth-first search than the execution time . In general, exponential-complexity search problems cannot be solved by uninformed search for any but the smallest instances .

3.4.2 Dijkstra’s algorithm or uniform-cost search 

When actions have different costs, an obvious choice is to use best-first search where the evaluation function is the cost of the path from the root to the current node. This is called Dijkstra’s algorithm by the theoretical computer science community, and uniform-cost search by the AI community.

The complexity of uniform-cost search is characterized in terms of \(C^*\) , the cost of the optimal solution, and \(\epsilon\) , a lower bound on the cost of each action, with \(\epsilon>0\) . Then the algorithm’s worst-case time and space complexity is \(O(b^{1+\lfloor C^*/\epsilon\rfloor})\) , which can be much greater than \(b^d\) .

When all action costs are equal, \(b^{1+\lfloor C^*/\epsilon\rfloor}\) is just \(b^{d+1}\) , and uniform-cost search is similar to breadth-first search.

3.4.3 Depth-first search and the problem of memory 

Depth-first search always expands the deepest node in the frontier first. It could be implemented as a call to \(Best\-First\-Search\) where the evaluation function \(f\) is the negative of the depth.

For problems where a tree-like search is feasible, depth-first search has much smaller needs for memory. A depth-first tree-like search takes time proportional to the number of states, and has memory complexity of only \(O(bm)\) , where \(b\) is the branching factor and \(m\) is the maximum depth of the tree.

A variant of depth-first search called backtracking search uses even less memory.

3.4.4 Depth-limited and iterative deepening search 

To keep depth-first search from wandering down an infinite path, we can use depth-limited search , a version of depth-first search in which we supply a depth limit, \(l\) , and treat all nodes at depth \(l\) as if they had no successors. The time complexity is \(O(b^l)\) and the space complexity is \(O(bl)\)

../_images/Fig3.12.png

Iterative deepening search solves the problem of picking a good value for \(l\) by trying all values: first 0, then 1, then 2, and so on—until either a solution is found, or the depth- limited search returns the failure value rather than the cutoff value.

Its memory requirements are modest: \(O(bd)\) when there is a solution, or \(O(bm)\) on finite state spaces with no solution. The time complexity is \(O(bd)\) when there is a solution, or \(O(bm)\) when there is none.

In general, iterative deepening is the preferred uninformed search method when the search state space is larger than can fit in memory and the depth of the solution is not known .

3.4.5 Bidirectional search 

An alternative approach called bidirectional search simultaneously searches forward from the initial state and backwards from the goal state(s), hoping that the two searches will meet.

../_images/Fig3.14.png

3.4.6 Comparing uninformed search algorithms 

../_images/Fig3.15.png

3.5 Informed (Heuristic) Search Strategies 

An informed search strategy uses domain–specific hints about the location of goals to find colutions more efficiently than an uninformed strategy. The hints come in the form of a heuristic function , denoted \(h(n)\) :

\(h(n)\) = estimated cost of the cheapest path from the state at node \(n\) to a goal state.

3.5.1 Greedy best-first search 

Greedy best-first search is a form of best-first search that expands first the node with the lowest \(h(n)\) value—the node that appears to be closest to the goal—on the grounds that this is likely to lead to a solution quickly. So the evaluation function \(f(n)=h(n)\) .

DEV Community

DEV Community

James saloman

Posted on Nov 8, 2023 • Updated on Nov 9, 2023

Introduction to Algorithms: What Every Beginner Should Know

Algorithms are the beating heart of computer science and programming. They are the step-by-step instructions that computers follow to solve problems and perform tasks. Whether you're a beginner or an aspiring programmer, understanding the fundamentals of algorithms is essential. In this blog post, we will introduce you to the world of algorithms, what they are, why they matter, and the key concepts every beginner should know.

What is an Algorithm?

At its core, an algorithm is a finite set of well-defined instructions for solving a specific problem or task. These instructions are executed in a predetermined sequence, often designed to transform input data into a desired output.

Think of algorithms as recipes: just as a recipe tells you how to prepare a meal, an algorithm tells a computer how to perform a particular task. But instead of cooking a delicious dish, you're instructing a computer to perform a specific computation or solve a problem.

Why Do Algorithms Matter?

Algorithms play a pivotal role in the world of computing for several reasons:

Efficiency: Well-designed algorithms can execute tasks quickly and use minimal resources, which is crucial in applications like search engines and real-time systems.

Problem Solving: Algorithms provide structured approaches to problem-solving and help us tackle complex issues more effectively.

Reusability: Once developed, algorithms can be used in various applications, promoting code reuse and reducing redundancy.

Scalability: Algorithms are essential for handling large datasets and growing computational needs in modern software.

Key Concepts in Algorithm Design

1. input and output.

Input: Algorithms take input data as their starting point. This could be a list of numbers, a text document, or any other data structure.

Output: Algorithms produce a result or output based on the input. This could be a sorted list, a specific calculation, or a solution to a problem.

2. Correctness

An algorithm is considered correct if it produces the desired output for all valid inputs. Ensuring correctness is a fundamental aspect of algorithm design and testing.

3. Efficiency

Efficiency is a critical consideration in algorithm design. It's about finding the most optimal way to solve a problem, which often involves minimizing the consumption of time and resources.

4. Scalability

Algorithms should be designed to handle input data of varying sizes efficiently. Scalable algorithms can adapt to growing data requirements without a significant decrease in performance.

5. Time Complexity and Space Complexity

Time complexity refers to the amount of time an algorithm takes to complete based on the size of the input. Space complexity concerns the amount of memory an algorithm requires. Understanding these complexities helps assess an algorithm's efficiency.

Examples of Common Algorithms

Sorting Algorithms: Algorithms like "Bubble Sort," "Quick Sort," and "Merge Sort" rearrange a list of items into a specific order.

Search Algorithms: Algorithms like "Binary Search" efficiently find a specific item in a sorted list.

Graph Algorithms: Algorithms like "Breadth-First Search" and "Dijkstra's Algorithm" navigate through networks and find optimal routes.

Dynamic Programming: Algorithms like the "Fibonacci Sequence" solver use a technique called dynamic programming to optimize problem-solving.

Algorithms are the building blocks of computer science and programming. While they might sound complex, they are at the heart of everything from internet search engines to your favorite social media platforms. As a beginner, understanding the basics of algorithms and their importance is a significant step in your coding journey.

As you dive into the world of algorithms, you'll discover that they can be both fascinating and challenging. Don't be discouraged by complex problems; instead, view them as opportunities to develop your problem-solving skills. Whether you're aiming to become a software developer, data scientist, or just a more proficient programmer, a solid grasp of algorithms is an invaluable asset. Happy coding! 🚀💡

Also, I have to tell you, this article was partially generated with the help of ChatGPT!!!

Top comments (1)

pic

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

jonrandy profile image

  • Location Bangkok 🇹🇭
  • Joined Jun 1, 2018

Hi there. This post reads a lot like it was generated or strongly assisted by AI. If so, please consider amending it to comply with the DEV.to guidelines concerning such content...

From " The DEV Community Guidelines for AI-Assisted and -Generated Articles ":

AI-assisted and -generated articles should… Be created and published in good faith, meaning with honest, sincere, and harmless intentions. Disclose the fact that they were generated or assisted by AI in the post, either upfront using the tag #ABotWroteThis or at any point in the article’s copy (including right at the end). - For example, a conclusion that states “Surprise, this article was generated by ChatGPT!” or the disclaimer “This article was created with the help of AI” would be appropriate. Ideally add something to the conversation regarding AI and its capabilities. Tell us your story of using the tool to create content, and why!

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

umida5 profile image

umida5 - Aug 21

khushbo_zahid_749 profile image

My Internship Experience with Code Alpha: Building Projects and Gaining Practical Skills

Khushbo Zahid - Aug 21

danieldevi profile image

From Idea to Launch: A Guide to Building Software Projects (For Solo Devs and Teams)

Daniel Agufenwa - Aug 21

kevinjudith profile image

First Contributions: learn how to contribute to open source projects

KevinJudith - Aug 21

DEV Community

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

Learn Python practically and Get Certified .

Popular Tutorials

Popular examples, reference materials, learn python interactively, dsa introduction.

  • What is an algorithm?
  • Data Structure and Types
  • Why learn DSA?
  • Asymptotic Notations
  • Master Theorem
  • Divide and Conquer Algorithm

Data Structures (I)

  • Types of Queue
  • Circular Queue
  • Priority Queue

Data Structures (II)

  • Linked List
  • Linked List Operations
  • Types of Linked List
  • Heap Data Structure
  • Fibonacci Heap
  • Decrease Key and Delete Node Operations on a Fibonacci Heap

Tree based DSA (I)

  • Tree Data Structure
  • Tree Traversal
  • Binary Tree
  • Full Binary Tree
  • Perfect Binary Tree
  • Complete Binary Tree
  • Balanced Binary Tree
  • Binary Search Tree

Tree based DSA (II)

  • Insertion in a B-tree
  • Deletion from a B-tree
  • Insertion on a B+ Tree
  • Deletion from a B+ Tree
  • Red-Black Tree
  • Red-Black Tree Insertion
  • Red-Black Tree Deletion

Graph based DSA

  • Graph Data Structure
  • Spanning Tree
  • Strongly Connected Components
  • Adjacency Matrix
  • Adjacency List
  • DFS Algorithm
  • Breadth-first Search

Bellman Ford's Algorithm

Sorting and Searching Algorithms

  • Bubble Sort
  • Selection Sort
  • Insertion Sort
  • Counting Sort
  • Bucket Sort
  • Linear Search
  • Binary Search

Greedy Algorithms

Greedy Algorithm

  • Ford-Fulkerson Algorithm
  • Dijkstra's Algorithm
  • Kruskal's Algorithm
  • Prim's Algorithm
  • Huffman Coding

Dynamic Programming

  • Floyd-Warshall Algorithm
  • Longest Common Sequence

Other Algorithms

  • Backtracking Algorithm
  • Rabin-Karp Algorithm

DSA Tutorials

Merge Sort Algorithm

  • Selection Sort Algorithm

What is an Algorithm?

In computer programming terms, an algorithm is a set of well-defined instructions to solve a particular problem. It takes a set of input(s) and produces the desired output. For example,

An algorithm to add two numbers:

Take two number inputs

Add numbers using the + operator

Display the result

Qualities of a Good Algorithm

  • Input and output should be defined precisely.
  • Each step in the algorithm should be clear and unambiguous.
  • Algorithms should be most effective among many different ways to solve a problem.
  • An algorithm shouldn't include computer code. Instead, the algorithm should be written in such a way that it can be used in different programming languages.

Algorithm Examples

Algorithm to add two numbers

Algorithm to find the largest among three numbers

Algorithm to find all the roots of the quadratic equation

Algorithm to find the factorial

Algorithm to check prime number

Algorithm of Fibonacci series

Algorithm 1: Add two numbers entered by the user

Algorithm 2: find the largest number among three numbers, algorithm 3: find roots of a quadratic equation ax 2 + bx + c = 0, algorithm 4: find the factorial of a number, algorithm 5: check whether a number is prime or not, algorithm 6: find the fibonacci series till the term less than 1000, table of contents.

  • Qualities of Good Algorithms
  • Add Two Numbers
  • Find Largest Number
  • Roots of Quatratic Equation
  • Find Factorial of a Number
  • Check Prime Number
  • Find Fibonacci Series

Sorry about that.

Our premium learning platform, created with over a decade of experience and thousands of feedbacks .

Learn and improve your coding skills like never before.

  • Interactive Courses
  • Certificates
  • 2000+ Challenges

Related Tutorials

DS & Algorithms

Have a language expert improve your writing

Check your paper for plagiarism in 10 minutes, generate your apa citations for free.

  • Knowledge Base
  • Using AI tools
  • What Is an Algorithm? | Definition & Examples

What Is an Algorithm? | Definition & Examples

Published on August 9, 2023 by Kassiani Nikolopoulou . Revised on August 29, 2023.

An algorithm is a set of steps for accomplishing a task or solving a problem. Typically, algorithms are executed by computers, but we also rely on algorithms in our daily lives. Each time we follow a particular step-by-step process, like making coffee in the morning or tying our shoelaces, we are in fact following an algorithm.

In the context of computer science , an algorithm is a mathematical process for solving a problem using a finite number of steps. Algorithms are a key component of any computer program and are the driving force behind various systems and applications, such as navigation systems, search engines, and music streaming services.

Instantly correct all language mistakes in your text

Upload your document to correct all your mistakes in minutes

upload-your-document-ai-proofreader

Table of contents

What is an algorithm, how do algorithms work, examples of algorithms, other interesting articles, frequently asked questions about algorithms.

An algorithm is a sequence of instructions that a computer must perform to solve a well-defined problem. It essentially defines what the computer needs to do and how to do it. Algorithms can instruct a computer how to perform a calculation, process data, or make a decision.

The best way to understand an algorithm is to think of it as a recipe that guides you through a series of well-defined actions to achieve a specific goal. Just like a recipe produces a replicable result, algorithms ensure consistent and reliable outcomes for a wide range of tasks in the digital realm.

And just like there are numerous ways to make, for example, chocolate chip cookies by following different steps or using slightly different ingredients, different algorithms can be designed to solve the same problem, with each taking a distinct approach but achieving the same result.

Algorithms are virtually everywhere around us. Examples include the following:

  • Search engines rely on algorithms to find and present relevant results as quickly as possible
  • Social media platforms use algorithms to prioritize the content that we see in our feeds, taking into account factors like our past behavior, the popularity of posts, and relevance.
  • With the help of algorithms, navigation apps determine the most efficient route for us to reach our destination.
  • It must be correct . In other words, it should take a given problem and provide the right answer or result, even if it stops working due to an error.
  • It must consist of clear, practical steps that can be completed in a limited time, whether by a person or the machine that must execute the algorithm. For example, the instructions in a cookie recipe might be considered sufficiently concrete for a human cook, but they would not be specific enough for programming an automated cookie-making machine.
  • There should be no confusion about which step comes next , even if choices must be made (e.g., when using “if” statements).
  • It must have a set number of steps (not an infinite number) that can be managed using loops (statements describing repeated actions or iterations).
  • It must eventually reach an endpoint and not get stuck in a never-ending loop.

Check for common mistakes

Use the best grammar checker available to check for common mistakes in your text.

Fix mistakes for free

Algorithms use a set of initial data or input , process it through a series of logical steps or rules, and produce the output (i.e., the outcome, decision, or result).

Algorithm boxes

If you want to make chocolate chip cookies, for instance, the input would be the ingredients and quantities, the process would be the recipe you choose to follow, and the output would be the cookies.

Algorithms are eventually expressed in a programming language that a computer can process. However, when an algorithm is being created, it will be people, not a computer, who will need to understand it. For this reason, as a first step, algorithms are written as plain instructions.

  • Input: the input data is a single-digit number (e.g., 5).
  • Transformation/processing: the algorithm takes the input (number 5) and performs the specific operation (i.e., multiplies the number by itself).
  • Output: the result of the calculation is the square of the input number, which, in this case, would be 25 (since 5 * 5 = 25).

We could express this as an algorithm in the following way:

Algorithm: Calculate the square of a number

  • Input the number (N) whose square you want to find.
  • Multiply the number (N) by itself.
  • Store the result of the multiplication in a variable (result).
  • Output the value of the variable (result), which represents the square of the input number.

It is important to keep in mind that an algorithm is not the same as a program or code. It is the logic or plan for solving a problem represented as a simple step-by-step description. Code is the implementation of the algorithm in a specific programming language (like C++ or Python), while a program is an implementation of code that instructs a computer on how to execute an algorithm and perform a task.

Instead of telling a computer exactly what to do, some algorithms allow computers to learn on their own and improve their performance on a specific task. These machine learning algorithms use data to identify patterns and make predictions or conduct data mining to uncover hidden insights in data that can inform business decisions.

Broadly speaking, there are three different types of algorithms:

  • Linear sequence algorithms follow a specific set or steps, one after the other. Just like following a recipe, each step depends on the success of the previous one.
  • For example, in the context of a cookie recipe, you would include the step “if the dough is too sticky, you might need to refrigerate it.”
  • For example, a looping algorithm could be used to handle the process of making multiple cookies from a single batch of dough. The algorithm would repeat a specific set of instructions to form and bake cookies until all the dough has been used.

Algorithms are fundamental tools for problem-solving in both the digital world and many real-life scenarios. Each time we try to solve a problem by breaking it down into smaller, manageable steps, we are in fact using algorithmic thinking.

  • Identify which clothes are clean.
  • Consider the weather forecast for the day.
  • Consider the occasion for which you are getting dressed (e.g., work or school etc.).
  • Consider personal preferences (e.g., style or which items match).

In mathematics, algorithms are standard methods for performing calculations or solving equations because they are efficient, reliable, and applicable to various situations.

Suppose you want to add the numbers 345 and 278. You would follow a set of steps (i.e., the standard algorithm for addition):

  • Write down the numbers so the digits align.
  • Start from the rightmost digits (the ones place) and add them together: 5 + 8 = 13. Write down the 3 and carry over the 1 to the next column.
  • Move to the next column (the tens place) and add the digits along with the carried-over value: 4 + 7 + 1 = 12. Write down the 2 and carry over the 1 to the next column.
  • Move to the leftmost column (the hundreds place) and add the digits along with the carried-over value: 3 + 2 + 1 = 6. Write down the 6.

The final result is 623

Algorithm calculation example

Navigation systems are another example of the use of algorithms. Such systems use algorithms to help you find the easiest and fastest route to your destination while avoiding traffic jams and roadblocks.

If you want to know more about ChatGPT, AI tools , fallacies , and research bias , make sure to check out some of our other articles with explanations and examples.

  • ChatGPT vs human editor
  • ChatGPT citations
  • Is ChatGPT trustworthy?
  • Using ChatGPT for your studies
  • Sunk cost fallacy
  • Straw man fallacy
  • Slippery slope fallacy
  • Red herring fallacy
  • Ecological fallacy
  • Logical fallacy

Research bias

  • Implicit bias
  • Framing bias
  • Cognitive bias
  • Optimism bias
  • Hawthorne effect
  • Unconscious bias

In computer science, an algorithm is a list of unambiguous instructions that specify successive steps to solve a problem or perform a task. Algorithms help computers execute tasks like playing games or sorting a list of numbers. In other words, computers use algorithms to understand what to do and give you the result you need.

Algorithms and artificial intelligence (AI) are not the same, however they are closely related.

  • Artificial intelligence is a broad term describing computer systems performing tasks usually associated with human intelligence like decision-making, pattern recognition, or learning from experience.
  • Algorithms are the instructions that AI uses to carry out these tasks, therefore we could say that algorithms are the building blocks of AI—even though AI involves more advanced capabilities beyond just following instructions.

Algorithms and computer programs are sometimes used interchangeably, but they refer to two distinct but interrelated concepts.

  • An algorithm is a step-by-step instruction for solving a problem that is precise yet general.
  • Computer programs are specific implementations of an algorithm in a specific programming language. In other words, the algorithm is the high-level description of an idea, while the program is the actual implementation of that idea.

Algorithms are valuable to us because they:

  • Form the basis of much of the technology we use in our daily lives, from mobile apps to search engines.
  • Power innovations in various industries that augment our abilities (e.g., AI assistants or medical diagnosis).
  • Help analyze large volumes of data, discover patterns and make informed decisions in a fast and efficient way, at a scale humans are simply not able to do.
  • Automate processes. By streamlining tasks, algorithms increase efficiency, reduce errors, and save valuable time.

Cite this Scribbr article

If you want to cite this source, you can copy and paste the citation or click the “Cite this Scribbr article” button to automatically add the citation to our free Citation Generator.

Nikolopoulou, K. (2023, August 29). What Is an Algorithm? | Definition & Examples. Scribbr. Retrieved August 26, 2024, from https://www.scribbr.com/ai-tools/what-is-an-algorithm/

Is this article helpful?

Kassiani Nikolopoulou

Kassiani Nikolopoulou

Other students also liked, what is deep learning | a beginner's guide, what is data mining | definition & techniques, what is machine learning | a beginner's guide, get unlimited documents corrected.

✔ Free APA citation check included ✔ Unlimited document corrections ✔ Specialized in correcting academic texts

  • Admiral “Amazing Grace” Hopper

Exploring the Intricacies of NP-Completeness in Computer Science

Understanding p vs np problems in computer science: a primer for beginners, understanding key theoretical frameworks in computer science: a beginner’s guide.

Learn Computer Science with Python

Learn Computer Science with Python

CS is a journey, not a destination

  • Foundations

Understanding Algorithms: The Key to Problem-Solving Mastery

example problem solving algorithms

The world of computer science is a fascinating realm, where intricate concepts and technologies continuously shape the way we interact with machines. Among the vast array of ideas and principles, few are as fundamental and essential as algorithms. These powerful tools serve as the building blocks of computation, enabling computers to solve problems, make decisions, and process vast amounts of data efficiently.

An algorithm can be thought of as a step-by-step procedure or a set of instructions designed to solve a specific problem or accomplish a particular task. It represents a systematic approach to finding solutions and provides a structured way to tackle complex computational challenges. Algorithms are at the heart of various applications, from simple calculations to sophisticated machine learning models and complex data analysis.

Understanding algorithms and their inner workings is crucial for anyone interested in computer science. They serve as the backbone of software development, powering the creation of innovative applications across numerous domains. By comprehending the concept of algorithms, aspiring computer science enthusiasts gain a powerful toolset to approach problem-solving and gain insight into the efficiency and performance of different computational methods.

In this article, we aim to provide a clear and accessible introduction to algorithms, focusing on their importance in problem-solving and exploring common types such as searching, sorting, and recursion. By delving into these topics, readers will gain a solid foundation in algorithmic thinking and discover the underlying principles that drive the functioning of modern computing systems. Whether you’re a beginner in the world of computer science or seeking to deepen your understanding, this article will equip you with the knowledge to navigate the fascinating world of algorithms.

What are Algorithms?

At its core, an algorithm is a systematic, step-by-step procedure or set of rules designed to solve a problem or perform a specific task. It provides clear instructions that, when followed meticulously, lead to the desired outcome.

Consider an algorithm to be akin to a recipe for your favorite dish. When you decide to cook, the recipe is your go-to guide. It lists out the ingredients you need, their exact quantities, and a detailed, step-by-step explanation of the process, from how to prepare the ingredients to how to mix them, and finally, the cooking process. It even provides an order for adding the ingredients and specific times for cooking to ensure the dish turns out perfect.

In the same vein, an algorithm, within the realm of computer science, provides an explicit series of instructions to accomplish a goal. This could be a simple goal like sorting a list of numbers in ascending order, a more complex task such as searching for a specific data point in a massive dataset, or even a highly complicated task like determining the shortest path between two points on a map (think Google Maps). No matter the complexity of the problem at hand, there’s always an algorithm working tirelessly behind the scenes to solve it.

Furthermore, algorithms aren’t limited to specific programming languages. They are universal and can be implemented in any language. This is why understanding the fundamental concept of algorithms can empower you to solve problems across various programming languages.

The Importance of Algorithms

Algorithms are indisputably the backbone of all computational operations. They’re a fundamental part of the digital world that we interact with daily. When you search for something on the web, an algorithm is tirelessly working behind the scenes to sift through millions, possibly billions, of web pages to bring you the most relevant results. When you use a GPS to find the fastest route to a location, an algorithm is computing all possible paths, factoring in variables like traffic and road conditions, to provide you the optimal route.

Consider the world of social media, where algorithms curate personalized feeds based on our previous interactions, or in streaming platforms where they recommend shows and movies based on our viewing habits. Every click, every like, every search, and every interaction is processed by algorithms to serve you a seamless digital experience.

In the realm of computer science and beyond, everything revolves around problem-solving, and algorithms are our most reliable problem-solving tools. They provide a structured approach to problem-solving, breaking down complex problems into manageable steps and ensuring that every eventuality is accounted for.

Moreover, an algorithm’s efficiency is not just a matter of preference but a necessity. Given that computers have finite resources — time, memory, and computational power — the algorithms we use need to be optimized to make the best possible use of these resources. Efficient algorithms are the ones that can perform tasks more quickly, using less memory, and provide solutions to complex problems that might be infeasible with less efficient alternatives.

In the context of massive datasets (the likes of which are common in our data-driven world), the difference between a poorly designed algorithm and an efficient one could be the difference between a solution that takes years to compute and one that takes mere seconds. Therefore, understanding, designing, and implementing efficient algorithms is a critical skill for any computer scientist or software engineer.

Hence, as a computer science beginner, you are starting a journey where algorithms will be your best allies — universal keys capable of unlocking solutions to a myriad of problems, big or small.

Common Types of Algorithms: Searching and Sorting

Two of the most ubiquitous types of algorithms that beginners often encounter are searching and sorting algorithms.

Searching algorithms are designed to retrieve specific information from a data structure, like an array or a database. A simple example is the linear search, which works by checking each element in the array until it finds the one it’s looking for. Although easy to understand, this method isn’t efficient for large datasets, which is where more complex algorithms like binary search come in.

Binary search, on the other hand, is like looking up a word in the dictionary. Instead of checking each word from beginning to end, you open the dictionary in the middle and see if the word you’re looking for should be on the left or right side, thereby reducing the search space by half with each step.

Sorting algorithms, meanwhile, are designed to arrange elements in a particular order. A simple sorting algorithm is bubble sort, which works by repeatedly swapping adjacent elements if they’re in the wrong order. Again, while straightforward, it’s not efficient for larger datasets. More advanced sorting algorithms, such as quicksort or mergesort, have been designed to sort large data collections more efficiently.

Diving Deeper: Graph and Dynamic Programming Algorithms

Building upon our understanding of searching and sorting algorithms, let’s delve into two other families of algorithms often encountered in computer science: graph algorithms and dynamic programming algorithms.

A graph is a mathematical structure that models the relationship between pairs of objects. Graphs consist of vertices (or nodes) and edges (where each edge connects a pair of vertices). Graphs are commonly used to represent real-world systems such as social networks, web pages, biological networks, and more.

Graph algorithms are designed to solve problems centered around these structures. Some common graph algorithms include:

Dynamic programming is a powerful method used in optimization problems, where the main problem is broken down into simpler, overlapping subproblems. The solutions to these subproblems are stored and reused to build up the solution to the main problem, saving computational effort.

Here are two common dynamic programming problems:

Understanding these algorithm families — searching, sorting, graph, and dynamic programming algorithms — not only equips you with powerful tools to solve a variety of complex problems but also serves as a springboard to dive deeper into the rich ocean of algorithms and computer science.

Recursion: A Powerful Technique

While searching and sorting represent specific problem domains, recursion is a broad technique used in a wide range of algorithms. Recursion involves breaking down a problem into smaller, more manageable parts, and a function calling itself to solve these smaller parts.

To visualize recursion, consider the task of calculating factorial of a number. The factorial of a number n (denoted as n! ) is the product of all positive integers less than or equal to n . For instance, the factorial of 5 ( 5! ) is 5 x 4 x 3 x 2 x 1 = 120 . A recursive algorithm for finding factorial of n would involve multiplying n by the factorial of n-1 . The function keeps calling itself with a smaller value of n each time until it reaches a point where n is equal to 1, at which point it starts returning values back up the chain.

Algorithms are truly the heart of computer science, transforming raw data into valuable information and insight. Understanding their functionality and purpose is key to progressing in your computer science journey. As you continue your exploration, remember that each algorithm you encounter, no matter how complex it may seem, is simply a step-by-step procedure to solve a problem.

We’ve just scratched the surface of the fascinating world of algorithms. With time, patience, and practice, you will learn to create your own algorithms and start solving problems with confidence and efficiency.

Related Articles

example problem solving algorithms

Three Elegant Algorithms Every Computer Science Beginner Should Know

What is a Greedy Algorithm? Examples of Greedy Algorithms

Tantoluwa Heritage Alabi

According to the Oxford English Dictionary, "greedy" means having excessive desire for something without considering the effect or damage done.

In computer science, a greedy algorithm is an algorithm that finds a solution to problems in the shortest time possible. It picks the path that seems optimal at the moment without regard for the overall optimization of the solution that would be formed.

Edsger Dijkstra, a computer scientist and mathematician who wanted to calculate a minimum spanning tree, introduced the term "Greedy algorithm". Prim and Kruskal came up with optimization techniques for minimizing cost of graphs.

Many Greedy algorithms were developed to solve graph problems. A graph is a structure made up of edges and vertices.

simple-graph-diagram

Greedy vs Not Greedy Algorithms

An algorithm is greedy when the path picked is regarded as the best option based on a specific criterion without considering future consequences. But it typically evaluates feasibility before making a final decision. The correctness of the solution depends on the problem and criteria used.

Example: A graph has various weights and you are to determine the maximum value in the tree. You'd start by searching each node and checking its weight to see if it is the largest value.

There are two approaches to solving this problem: greedy approach or not greedy.

example-graph

This graph consists of different weights and we need to find the maximum value. We'll apply the two approaches on the graph to get the solution.

Greedy Approach

In the images below, a graph has different numbers in its vertices and the algorithm is meant to select the vertex with the largest number.

Starting from vertex 6, then it's faced with two decisions – which is bigger, 3 or 4? The algorithm picks 4, and then is faced with another decision – which is bigger, 14 or 11. It selects 14, and the algorithm ends.

On the other hand there is a vertex labeled 20 but it is attached to vertex 3 which greedy does not consider as the best choice. It is important to select appropriate criteria for making each immediate decision.

greedy-approach-graph

Not Greedy Approach

The “not greedy” approach checks all options before arriving at a final solution, unlike the "greedy approach" which stops once it gets its results.

Starting from vertex 6, then it's faced with two decisions – which is bigger, 3 or 4? The algorithm picks 4, and then is faced with another decision – which is bigger, 14 or 11. It selects 14 and keeps it aside.

Then it runs the process again, starting from vertex 6. It selects the vertex with 3 and checks it. 20 is attached to the vertex 3 and the process stops. Now it compares the two results – 20 and 14. 20 is bigger, so it selects the vertex (3) that carries the largest number and the process ends.

This approach considers many possibilities in finding the better solution.

non-greedy-approach-graph

Characteristics of a Greedy Algorithm

  • The algorithm solves its problem by finding an optimal solution. This solution can be a maximum or minimum value. It makes choices based on the best option available.
  • The algorithm is fast and efficient with time complexity of O(n log n) or O(n). Therefore applied in solving large-scale problems.
  • The search for optimal solution is done without repetition – the algorithm runs once.
  • It is straightforward and easy to implement.

How to Use Greedy Algorithms

Before applying a greedy algorithm to a problem, you need to ask two questions:

  • Do you need the best option at the moment from the problem?
  • Do you need an optimal solution (either minimum or maximum value)?

If your answer to these questions is "Yes", then a greedy algorithm is a good choice to solve your problem.

Let’s assume you have a problem with a set of numbers and you need to find the minimum value.

You start of by defining the constraint, which in this case is finding the minimum value. Then each number will be scanned and checked on each constraint which serves as a condition to be fulfilled. If the condition is true, the number(s) is selected and returned as the final solution.

Here's a flowchart representation of this process:

greedy-algorithm-flow-chart

Greedy Algorithm Examples

Problem 1 : activity selection problem.

This problem contains a set of activities or tasks that need to be completed. Each one has a start and finish time. The algorithm finds the maximum number of activities that can be done in a given time without them overlapping.

Approach to the Problem

  • We have a list of activities. Each has a start time and finish time.
  • First, we sort the activities and start time in ascending order using the finish time of each.
  • Then we start by picking the first activity. We create a new list to store the selected activity.
  • To choose the next activity, we compare the finish time of the last activity to the start time of the next activity. If the start time of the next activity is greater than the finish time of the last activity, it can be selected. If not we skip this and check the next one.
  • This process is repeated until all activities are checked. The final solution is a list containing the activities that can be done.

The table below shows a list of activities as well as starting and finish times.

start-and-finish-times-1

The first step is to sort the finish time in ascending order and arrange the activities with respect to the result.

start-and-finish-times-2

After sorting the activities, we select the first activity and store it in the selected activity list. In our example, the first activity is “Homework”.

Moving to the next activity, we check the finish time of “Homework” (5)  which was the last activity selected and the starting time of “Term paper” (4). To pick an activity, the starting time of the next activity must be greater than or equal to the finish time. (4) is less than (5), so we skip the activity and move to the next.

The next activity “Presentation” has a starting time of (6) and it is greater than the finish time (5) of “Homework”. So we select it and add it to our list of selected activities.

For the next activity, we do the same checking. Finish time of “Presentation” is (10), starting time of “Volleyball practice ” is (10). We see that the starting time is equal to the finish time which satisfies one of the conditions, so we select it and add it to our list of selected activities.

Continuing to the next activity, the finish time of “Volleyball” practice is (12) and the starting time of “Biology lecture” is (13). We see the starting time is greater than the finish time so we select it.

For our last activity, the starting time for “Hangout” is (7) and the finishing time of our last activity “Biology lecture” is (14), 7 is less than 14, so we cannot select the activity. Since we are at the end of our activity list, the process ends.

Our final result is the list of selected activities that we can do without time overlapping: {Homework, Presentation, Volleyball practice, Biology lecture}.

Code Implementation of the Example

The variable <data> stores the starting times of each activity, the finish time of each activity, and the list of tasks (or activities) to be performed.

The variable <selected_activity> is an empty list that will store the selected activities that can be performed.

<start_position> shows the position the first activity which is index “0”. This will be our starting point.

Here's a dataframe table showing the original data:

Then we sort the finish time in ascending order and rearrange the start time and activity in respect to it. We target the variables by using the keys in the dictionary.

In the code above, we intialized <tem> to zero. We are not using the inbuilt method to sort the finish time. We are using two loops to arrange it in ascending order.   <i> and <j> represent the indexes and check if values of the <data['finish_time'][i]>  is less than <data['finish_time'][j]> .

If the condition is true, <tem> stores the values of the elements in the <i> position and swaps the corresponding element.

Now we print the final result, here's what we get:

And here's a dataframe table showing the sorted data:

After sorting the activities, we start by selecting the first activity, which is “Homework”. It has a starting index of “0” so we use the <start_position> to target the activity and append it to the empty list.

The condition for selecting an activity is that the start time of the next activity selected is greater than the finish time of the previous activity. If the condition is true, the selected activity is added to the <selected_activity> list.

Here's what it looks like all together:

Problem 2: Fractional Knapsack Problem

A knapsack has a maximum weight, and it can only accommodate a certain set of items. These items have a weight and a value.

The aim is to fill the knapsack with the items that have the highest total values and do not exceed the maximum weight capacity.

There are two elements to consider: the knapsack and the items. The knapsack has a maximum weight and carries some items with a high value.

Scenario: In a jewelry store, there are items made of gold, silver, and wood. The costliest item is gold followed by silver and then wood. If a jewerly thief comes to the store, they take gold because they will make the most profit.

The thief has a bag (knapsack) that they can put those items in. But there is a limit to what the thief can carry because these items can get heavy. The idea is to pick the item the makes the highest profit and fits in the bag (knapsack) without exceeding its maximum weight.

  • The first step is to find the value to weight ratio of all items to know what fraction each one occupies.
  • We then sort these ratios in descending order (from highest to lowest ). This way we can pick the ratios with the highest number first knowing that we will make a profit.
  • When we pick the highest ratio, we find the corresponding weight and add it to the knapsack. There are conditions to be checked.

Condition 1 : If the item added has a lesser weight than the maximum weight of the knapsack, more items are added until the sum of all the items in the bag are the same as the maximum weight of the knapsack.

Condition 2 : If the sum of the items’ weight in the bag is more than the maximum capacity of the knapsack, we find the fraction of the last item added. To find the fraction, we do the following:

  • We find the sum of the remaining weights of the items in the knapsack. They must be less than the maximum capacity.
  • We find the difference between the maximum capacity of the knapsack and the sum of the remaining weights of the items and divide by the weight of the last item to be added.

To add the weight of the last item to the knapsack, we multiply the fraction by the weight.

When we sum up the weights of all the items it will be equal to the knapsack's maximum weight.

Practical Example:

Let's say that the maximum capacity of the knapsack is 17, and there are three items available. The first item is gold, the second item is silver, and third item is wood.

  • Weight of gold is 10, the weight of silver is 6, and the weight of wood is 2
  • the value (profit) of gold is 40, the value (profit) of silver is 30, and the value (profit) of wood is 6.
  • Ratio of gold= value/weight = 40/10 = 4
  • Ratio of silver = value/weight=30/6 = 5
  • Ratio of wood = value/weight = 6/2 = 3
  • Arranging the ratios in descending: 5, 4, 3.
  • The largest ratio is 5 and we match it to the corresponding weight “6”. It points to silver.
  • We put silver in the knapsack first and compare it to the maximum weight which is 17. 6 is less than 17 so we have to add another item. Going back to the ratios, the second largest is “4” and it corresponds to the weight of “10” which points to gold.
  • Now, we put gold in the knapsack, add the weight of the silver and gold, and compare it with the knapsack weight. (6 + 10 = 16). Checking it against the maximum weight, we see that it is less. So we can take another item. We go back to the list of ratios and take the 3rd largest which is “3” and it corresponds to “2” which points to wood.
  • When we add wood in the knapsack, the total weight is (6 +10+2 = 18) but that is greater than our maximum weight which is 17. We take out the wood from the knapsack and we are left with gold and silver. The total sum of the two is 16 and the maximum capacity is 17. So we need a weight of 1 to make it equal. Now we apply condition 2 discussed above to find the fraction of wood to fit in the knapsack.

frac1

Now the knapsack is filled.

The variable <data> stores the weights of each item and the profits. The variable <maximum_capacity> stores the maximum weight of the knapsack. <selected_wt> is intialized at 0, and it will store the selected weights to be put in the knapsack. Lastly, <max_profit> is intialized as 0, it will store the values of the selected weight.

Then we calculate the ratio of the profit to the weight. Ratio = profit/weight:

Now that we have the ratio, we arrange the elements in descending order, from biggest to smallest. Then the items in weight and profit are arranged according to the positions of the sorted ratio.

After the weight and profit are sorted, we start choosing the items and checking the condition. We loop through the length of ratio to target the index of each item in the list. Note: all items in ratio are arranged from biggest to smallest, so the first item is the maximum value and the last item is the minimum value.

The first item we select has the highest ratio amongst the rest and it is in index 0. Now that the first weight is selected weight, we check if it is less than maximum weight. If it is, we add items till the total weight is equal to the weight of the knapsack. The second item we select has the second highest ratio amongst the rest and it is in index 1, the arrangement is that order of selection.

For every selected weight, we add it to the selected_wt  variable and their corresponding profits to the max_profit variable.

When the sum of the selected weights in the knapsack exceeds the maximum weight, we find the fraction of the weight of the last item added to make the total selected weights be equal to the maximum weight. We do this by finding the difference between the max_weight and the sum of the selected weights divided by the weight of the last item added.

The final profit made from the fraction carried is added to the max_profit variable. Then we return the max_profit as the final result.

Bringing it all together:

Applications of Greedy Algorithms

There are various applications of greedy algorithms. Some of them are:

  • Minimum spanning tree is without any cycles and with the minimum possible total edge weight. This tree is derived from a connected undirected graph with weights.
  • Dijkstra’s shortest path is a search algorithm that finds the shortest path between a vertex and other vertices in a weighted graph.
  • Travelling salesman problem involves finding the shortest route that visits different places only once and returns to the starting point
  • Huffman coding assigns shorter code to frequently occurring symbols and longer code to less occurring symbols. It is used to encode data efficiently.

Advantages of Using a Greedy Algorithm

Greedy algorithms are quite straight forward to implement and easy to understand. They are also very efficient and have a lower complexity time of  O(N * logN).

They're useful in solving optimization problems, returning a maximum or minimum value.

Disadvantages/Limitations of Using a Greedy Algorithm

Even though greedy algorithms are straightforward and helpful in optimization problems, they don't offer the best solutions at all times.

Also greedy algos only run once, so they don't check the correctness of the result produced.

Greedy algorithms are a straightforward approach to solving optimization problems, returning a minimum or maximum value.

This article explained some examples of greedy algorithms and the approach to tackling each problem. By understanding how a greedy algorithm problems works you can better understand dynamic programming. If you have any questions feel free to reach out to me on Twitter 💙.

Read more posts .

If you read this far, thank the author to show them you care. Say Thanks

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

Sphero makes remarkably cool, programmable robots and STEAM-based educational tools that transform the way kids learn, create and invent through coding, science, music, and the arts.

  • Teacher Resources
  • Funding & Grants
  • Sphero Global Challenge
  • Shop by Product
  • Blueprint Engineering
  • Professional Development
  • Shop by Age
  • Early Learning
  • Middle School
  • High School
  • Sphero Central
  • Lessons & Resources
  • App Downloads
  • Standards Alignment
  • ESSER & American Rescue Plan
  • Federal & State
  • Corporate & Organizational
  • Crowdfunding
  • Sample RFP/Grant Language
  • Schedule a Virtual Demo
  • Age Brackets
  • Early Elementary
  • Upper Elementary
  • Manage Your Team

Sphero logo

Enter your e-mail and password:

New customer? Create your account

Lost password? Recover password

Recover password

Enter your email:

Remembered your password? Back to login

Create my account

Please fill in the information below:

Already have an account? Login here

6 Examples of Algorithms In Everyday Life

Algorithms are all around us in the real world, like traffic lights, and how they work.

We teach our kids from a very early age how to do everyday tasks. We show them how to tie their shoes, walk up the stairs, snap their fingers, whistle, and even how to set the table using a step-by-step procedure. 

From following a recipe to driving a car, everything we do has a process to follow. As kids grow and face more complex problems to solve, they need a strong foundation in algorithmic design and computational thinking to accomplish their goals.

Algorithms and computational thinking are so important for young learners because they teach kids how to solve problems and develop step-by-step processes, both at school and outside the classroom. 

We asked two STEM education experts, Laurie Guyon and David Czechowski, how they best explain real-world algorithm examples to their students and compiled them here. 

What is an algorithm?

An algorithm is a set of rules or instructions used to solve complex problems. In many STEM fields, algorithms are used by computer programs to streamline processes. However, algorithms aren’t limited to STEM; they’re found everywhere.

Why Algorithms are Important in Early Education

Algorithms are in everything we do. They’re a crucial part of computational thinking and problem-solving in many areas of life, as we use algorithms to accurately and efficiently execute tasks. 

Laurie Guyon, Sphero Hero and Coordinator for Model Schools in New York, shared, “As a former sixth-grade English teacher, I used algorithmic design in essay writing to talk about sequencing, storyboarding, plot diagrams, and following steps to write a quality essay. We even called the editing process ‘debugging,’ because I found students were more likely to edit their papers if they saw the purpose of making sure their writing made sense to the reader. If we discussed their sentences as lines of code that a human had to read, they understood the importance of the editing process.”

The same can be said for just about anything we do. If you have ever watched a cooking show, the chef walks you through the step-by-step process of creating a delicious meal. Someone who investigates crime has a procedure to discern what happened in an incident and who could be at fault. Algorithms are in everything we do, so it’s important that young learners understand how to recognize and utilize them, Guyon adds.

6 Examples of Real-World Algorithms

Whether algorithms are used in places that aren’t at all surprising, like Google, or in a manual activity that is more unexpected, like brushing your teeth, algorithms play a role in the human experience every single day, Guyon goes on to explain.

1. Sorting Papers

A teacher sorting papers in alphabetical order is an example of a real-world algorithm.

Imagine a teacher sorting their students’ papers according to the alphabetical order of their first names. This type of task is similar to the function of a sorting algorithm, like a bucket sort . By looking at only the first letter of the first name, you can remove a lot of unnecessary information. This is an automated process that makes sorting more efficient.

2. Facial Recognition

Every day we see someone we know: a loved one, a coworker, or even an eccentric neighbor. When we recognize somebody’s face, we’re drawing upon data we’ve previously collected on the size and position of that person’s facial features. That information is then analyzed internally to automatically recognize others.

Facial recognition, both through people we know and through technology, is an example of a real-world algorithm.

Algorithms can automate this process for computers; however, facial recognition is not perfect. In the Netflix series “ Coded Bias ,” Joy Buolamwini, an activist and computer scientist based at MIT, discusses how algorithms used for facial recognition can be biased. This investigative series finds that facial recognition algorithms often do not recognize dark-skinned faces accurately, uncovering the need for additional work when creating algorithms based on human design.

3. Google Search

Even an action as seemingly simple as a Google search is only possible with the help of algorithms. Say, for example, you want to know if an elephant can swim. How you phrase the question to Google is the input you are asking the computer to determine. 

Google search is a good example of a real-world algorithm.

Google doesn’t even need all the words of the question “can an elephant swim?” For example, try searching for “swimming elephant” and see what you get. You will find that immediately, the output or the results show videos of elephants swimming, followed by more on the subject. Google uses an algorithm to generate these answers without needing the entirety of the question.

4. Duplicating Outcomes  

A teenage boy references a cookbook in the kitchen. Following a recipe is a good example of real-world algorithms in action.

David Czechowski, Computer Science and Technology Teacher at Hyde Park Central Schools , explains this example. “If we want to do well at a given task, it can be extremely helpful to look at previous successful examples from other people. A great daily example of this is using a recipe while cooking. Sure, you might be able to figure out how to make delicious pasta on your own through trial and error, but following a step-by-step recipe from a well-known chef helps ensure success.”

5. Traffic Lights

Czechowski adds, “Here’s an algorithm we frequently experience; the next time you're in your car stuck at a red light, consider the algorithm the traffic light is executing.”

Traffic lights are a great example of how algorithms are used in the real world, all around us.

Most traffic lights don’t automatically cycle through green, yellow, and red. Rather, there are sensory inputs that determine the signals’ timing based on the flow of traffic. The algorithm is a well-constructed, step-by-step order that directs the traffic appropriately (although it may not feel like it when you’re sitting at a red light). 

6. Bus Schedules

Every weekday morning, thousands of buses criss-cross neighborhoods picking up students. Mapping out efficient bus routes is an overwhelming manual task to execute without an algorithm to automate the calculations and schedule the right students for the right addresses at the right time. This routing issue is classically referred to as “ The Traveling Salesman Problem " and is even used as an exercise for theoretical computer science, according to Czechowski.

A woman waits for a bus. The schedule busses follow to make on-time arrivals and departures is an example of a real-world algorithm.

Algorithms are all around us, so close and common that we don’t even recognize them as algorithms. From cooking to looking up directions to something simple like tying your shoes, finding algorithms in your day-to-day life may not be as hard as you think.

How Administrators Can Build Confidence with Algorithms

Algorithmic thinking should be a crucial facet in modern education programs, but many schools overlook this topic or are unsure how to approach it. Administrators can take steps to ensure that algorithmic thinking and design are present in their schools.

Administrator’s Corner: Algorithmic thinking can also improve the onboarding or upskilling of teachers. 

When designing professional learning opportunities for current or future teachers, I like to follow an outline or an algorithmic process. I start with a question or activity to get participants engaged, build community, and think about the topic. From there, I like to do something to get them excited about the subject. We dive into the meat of the matter, with lots of time for questions and reflection. This algorithm allows participants to be actively engaged in the learning process and keeps a natural flow for success.

Show Real-World Examples of Algorithms with Sphero

Algorithm design doesn’t have to be complex or daunting. It already plays an important role in our daily lives, even in the simplest tasks we do like Googling questions or organizing papers. Algorithmic thinking is an integral part of computational thinking and is now a necessary life skill.

Young learners can develop algorithmic thinking and design skills both in and out of the classroom with the help of Sphero’s programmable robots and STEM kits .

example problem solving algorithms

Written by:

Sphero Team

Keep your inbox inspired. Sign up for product updates, exclusive offers, and teacher resources.

Popular posts

Sphero Heroes posing for picture together.

Featured products

Sphero BOLT Power Pack + Sphero City and Golf Code Mat.

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

Simple array sum easy problem solving (basic) max score: 10 success rate: 94.54%, compare the triplets easy problem solving (basic) max score: 10 success rate: 95.84%, a very big sum easy problem solving (basic) max score: 10 success rate: 98.82%, diagonal difference easy problem solving (basic) max score: 10 success rate: 96.03%, plus minus easy problem solving (basic) max score: 10 success rate: 98.39%, staircase easy problem solving (basic) max score: 10 success rate: 98.37%, mini-max sum easy problem solving (basic) max score: 10 success rate: 94.46%, birthday cake candles easy problem solving (basic) max score: 10 success rate: 97.15%, time conversion easy problem solving (basic) max score: 15 success rate: 92.39%, cookie support is required to access hackerrank.

Seems like cookies are disabled on this browser, please enable them to open this website

A blue and black logo

  • November 5, 2019

What Are Algorithms? A Guide to Algorithms for Children

example problem solving algorithms

We live in a world where technology is constantly changing at an impressive pace. In fact, many older parents already find it difficult to keep up with some of the new gadgets and latest upgrades to familiar software, but it isn’t like that for kids. Today’s children have more exposure to technology compared to previous decades. With things like AI, natural language processing (NLP), or virtual reality, many expect even more changes in the coming years. So what can you do?

Turns out you can help your kids right now to learn vital skills that will equip them for the future. Children of all ages can learn complex concepts in an interactive game-like online environment that covers everything from basic topics like “what are algorithms” to more advanced skills. Good algorithm training can help kids develop their critical thinking and problem-solving abilities. Besides, they get to build vital skills for future-relevant careers. In this article, we have covered some of the essential details to help you understand how the algorithm works.

What Is an Algorithm?

An algorithm definition is as simple as a set of step-by-step procedures or a list of rules to follow for completing a specific task or solving a particular problem. Even though the word ‘algorithm’ was first coined in the 9th century, they are all around us until today. Common algorithm examples include the recipe for baking a cake, the method we use to solve a long division problem, the process of doing laundry, and the workflow of Google’s search algorithm. Here’s what baking a cake might look like, written out as a list of instructions, just like an algorithm:

  • Gather all the ingredients
  • Preheat the oven
  • Measure out the ingredients
  • Mix together the ingredients to make the batter
  • Grease a pan and pour the batter into the pan
  • Put the pan in the oven
  • Set a timer
  • When the timer goes off, take the pan out of the oven

This is a simple example of a data structure, meaning the organized sequence of procedures, numbers, etc. In computer science, an algorithm works similarly – it is all about writing a set of rules with a finite number of steps that tell the computer how to perform a task. A computer program is essentially an algorithm that indicates what specific actions a machine should execute to carry out any task. Algorithms are written using a particular syntax, depending on the programming language.

Types of Algorithms

Apart from the algorithm’s meaning, you should also distinguish their varieties. They are classified based on the concepts used to accomplish a task. While there are many types of algorithms, the most basic programming algorithm examples are:

  • Divide and conquer algorithms. This one divides a problem into smaller ones of the same kind. Next, it solves those minor issues and comes up with a solution to the original problem. Neat, huh?
  • Brute force algorithms. If you have seen anyone trying to open a locked door when they have lost their keys, then you have a pretty good idea of how this works. This programming algorithm example will basically try all possible solutions until a satisfactory one is found. It’s kind of like you hit your lock with a hammer until it breaks open.
  • Randomized algorithms. Everyone has tried to guess an answer to something before. Turns out you can do the same using an algorithm. You can try using a random number at least once during the calculations to find a solution to the problem.
  • Greedy algorithms. This one is easy to guess. It tries to find the best solution at the local level to locate the best possible answer for the entire issue right away.
  • Recursive algorithms. Remember that time you answered the simplest test questions before doing the tough ones. It’s the same thing here. Recursive algorithms solve the lowest and easiest version of a problem before moving to the increasingly larger versions of the issue. They do this until the solution to the original problem is found.
  • Backtracking algorithms. This one is a bit like the first one but with a twist. This works by dividing the problem into subproblems and then trying to solve each of the little issues. But if it doesn’t find the right solution, it will move backward into the first problem until it finds the right path.
  • Dynamic programming algorithms. This is another simple example of an algorithm. First, break a complex problem into a collection of simpler and smaller ones. Then, solve each of those minor issues only once, storing their solution for later instead of re-computing their solutions again and again.
  • Sorting Algorithms. This sorts the elements of a list in a particular order, usually in numerical or lexicographical (i.e., alphabetical) order. This is an essential first step that makes it possible for the algorithms to solve more complex problems. There are different sorting systems, such as:
  • Linear sort: Find the smallest element in the list to be sorted, add it to a new list, and remove it from the original list. Repeat this until you go through the whole original data set.
  • Bubble sort: Compare the first two elements in the list, and if the first is greater than the second, swap them. Do this with every pair of adjacent elements in the set. Then, repeat this process until the list is fully sorted.
  • Insertion sort: Compare each element in the list to all the prior ones until you find the smallest value. Then, locate the right spot for each component based on the order you try to achieve. Repeat this process until you fully sort the initial list.

Example of an Algorithm – Solving a Rubik’s Cube

There are a number of different algorithms, from simple to very complicated, that exist for solving a Rubik’s cube . Below is just one simple algorithm example that significantly reduces the amount of time spent on solving this famous puzzle. First, let’s specify some important details (similarly to picking a programming language).

Each of the six faces of a Rubik’s cube can be represented by the first letter of their name:

  • U – up
  • D – down
  • L – left
  • R – right
  • F – front
  • B – back

Each face can be turned in three different ways/directions. Using U as an example, these are represented as:

  • U – clockwise quarter-turn of the upper face
  • U’ – counter-clockwise quarter-turn of the upper face
  • U2 – half turn in either direction of the upper face

Now, let’s go through the steps in our example of an algorithm to solve a Rubik’s Cube. Feel free to grab one of your own and follow along!

Step #1: The Cross

First, you should flip some edges to get a white cross on the upper face. To do that, apply the following turns: F → R’ → D’ → R → F2 → R’ → U → R → U’ → R’ → R2 → L2 → U2 → R2 → L2.

The cross is now solved!

Step #2: The White Corners

The edges on the white face are now complete, but the corners remain. Depending on where the white-orange-green corner is in the puzzle, apply one of the following series of turns:

  • Bottom: R’ → D’ → R → D (repeat until the corner moves to its correct place)
  • Top: R’ → D’ → R → D (this moves the corner to the bottom; then, follow the above instructions)

Step #3: Middle Layer Edges

Now that you have your corners in place, follow these steps:

  • Flip the cube so that the white is on the bottom.
  • Look for an edge that is on the top face and doesn’t have yellow on it.
  • Perform a U-turn so that the color on the front face of the edge matches with the center.
  • Depending on the direction that the edge could go, apply one of the following series of turns:
  • Left: U’ → L’ → U → L → U → F → U’ → F’
  • Right: U → R → U’ → R’ → U’ → F’ → U → F

Step #4: Yellow Cross

As our next step, let’s solve the yellow cross. To do that, follow these instructions:

  • Apply the following turns until you see a yellow cross with the yellow center: F → R → U → R’ → U’ → F’.
  • If there is an “L” shape, where the two yellow pieces showing are adjacent to each other, apply the following turns: F → U → R → U’ → R’ → F’.
  • If there is a horizontal “line” shape, apply the following turns: F → R → U → R’ → U’ → F’.

Step #5: Sune and Antisune

When you have your yellow cross ready, face it and apply one of the following series of turns:

  • If there is only one oriented corner, follow these turns: R → U → R’ → U → R → U2 → R’ (repeat until the desired position is attained).
  • In case there is one oriented corner and one right-facing corner, here is a solution: U2 → R → U2 → R’ → U’ → R → U’ → R’.

Step #6: Finishing the puzzle

You are just one step away from completing our algorithm example – solving your Rubik’s Cube. To finish up, follow this guidance:

  • Look for sets of “headlights” (two stickers of the same color in the same row, separated by a sticker of a different color).
  • Depending on how many there are, apply one of the following series of turns:
  • If there is a set of headlights on each side, follow this combination: R → U’ → R → U → R → U → R → U’ → R’ → U’ → R2.
  • Otherwise, these are the turns you need: R’ → F → R’ → B2 → R → F’ → R’ → B2 → R2.

How Are Algorithms Used in Computer Science?

Algorithms are used in every part of computer science, and there are countless programming algorithm examples as they form this field’s backbone. Consider these a few of the use cases:

  • An algorithm gives the machine a specific set of instructions, defining every process the system does, whether running a calculator or a rocket.
  • Computer programs are, at their core, algorithms written in programming languages that the machine can understand.
  • Computer algorithms play a big role in how social media works: which posts show up, which ads are shown, and so on. These decisions are all made by algorithms. Google’s programmers use algorithms to optimize searches, predict what users are going to type, and more.
  • In problem-solving, a big part of computer programming is learning about the formation and analysis of algorithms.

Algorithmic thinking, or the ability to define clear steps to solve a problem, is crucial in many different fields, including machine learning (ML) and artificial intelligence (AI). Even if we’re not conscious of it, we use algorithms all the time. Knowing the answer to “What are algorithms?” and understanding algorithmic thinking allows students like you to break down problems and picture distinct steps and solutions. Being able to understand and implement an algorithm requires practicing logic and reasoning abilities. To further dive into the subject, read how programming algorithms help develop logical thinking skills .

example problem solving algorithms

Juni Learning’s Coding Hackathon Winners: Summer 2024

Diya showing her new book Vacation Mysteries The Magic Box

Juni Student Spotlight: Diya Cheruku — Published Teen Novelist

Python coding classes for kids

Python Coding Classes for Kids: This Is How to Start

Go further with juni.

Find your potential through our exclusive educational content, guides, and resources only available to Juni Subscribers.

Recent Posts

Looking for a juni course check out our course explorer.

EXPLORE ALL COURSES >>

Dad and son

Get fun activities sent straight to your inbox

Enjoyed this article? Become a Juni subscriber to get even more exclusive educational content, guides, and deals sent straight to your email inbox.

Investing & Entrepreneurship

Communications

Help with Schoolwork

All Courses

How It Works

Instructors

Student Projects

On Demand ACT & SAT Prep

Help Center & FAQ

Founders’ Story

Instructor Jobs

Our Policies

Subscribe to our newsletter

Learn about our latest events, resources, programs, and more!

By subscribing you agree with our Terms of Use & Privacy Policy .

2261 Market St #4242, San Francisco, CA 94114

[email protected]

Discover more from Juni Learning

Subscribe now to keep reading and get access to the full archive.

Type your email…

Continue reading

  • DSA Tutorial
  • Data Structures
  • Linked List
  • Dynamic Programming
  • Binary Tree
  • Binary Search Tree
  • Divide & Conquer
  • Mathematical
  • Backtracking
  • Branch and Bound
  • Pattern Searching

What is Algorithm | Introduction to Algorithms

Definition of algorithm.

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.

What is Algorithm

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?

  • Algorithms are necessary for solving complex problems efficiently and effectively. 
  • They help to automate processes and make them more reliable, faster, and easier to perform.
  • Algorithms also enable computers to perform tasks that would be difficult or impossible for humans to do manually.
  • 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?

 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 are an algorithm. For some instructions to be an algorithm, it must have the following characteristics:

  • Clear and Unambiguous : The algorithm should be unambiguous. Each of its steps should be clear in all aspects and must lead to only one meaning.
  • Well-Defined Inputs : If an algorithm says to take inputs, it should be well-defined inputs. It may or may not take input.
  • Well-Defined Outputs: The algorithm must clearly define what output will be yielded and it should be well-defined as well. It should produce at least 1 output.
  • Finite-ness: The algorithm must be finite, i.e. it should terminate after a finite time.
  • Feasible: The algorithm must be simple, generic, and practical, such that it can be executed with the available resources. It must not contain some future technology or anything.
  • Language Independent: The Algorithm designed must be language-independent, i.e. it must be just plain instructions that can be implemented in any language, and yet the output will be the same, as expected.
  • Input : An algorithm has zero or more inputs. Each that contains a fundamental operator must accept zero or more inputs.
  •   Output : An algorithm produces at least one output. Every instruction that contains a fundamental operator must accept zero or more inputs.
  • Definiteness: All instructions in an algorithm must be unambiguous, precise, and easy to interpret. By referring to any of the instructions in an algorithm one can clearly understand what is to be done. Every fundamental operator in instruction must be defined without any ambiguity.
  • Finiteness: An algorithm must terminate after a finite number of steps in all test cases. Every instruction which contains a fundamental operator must be terminated within a finite amount of time. Infinite loops or recursive functions without base conditions do not possess finiteness.
  • Effectiveness: An algorithm must be developed by using very basic, simple, and feasible operations so that one can trace it out by using just paper and pencil.

Properties of Algorithm:

  • It should terminate after a finite time.
  • It should produce at least one output.
  • It should take zero or more input.
  • It should be deterministic means giving the same output for the same input case.
  • Every step in the algorithm must be effective i.e. every step should do some work.

Types of Algorithms:

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

1. Brute Force Algorithm :

It is the simplest approach to 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 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 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 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 for the next part is built based on the immediate benefit of the next part. The one solution that gives 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:

  • It is easy to understand.
  • An algorithm is a step-wise representation of a solution to a given problem.
  • In an Algorithm the problem is broken down into smaller pieces or steps hence, it is easier for the programmer to convert it into an actual program.

Disadvantages of Algorithms :

  • Writing an algorithm takes a long time so it is time-consuming.
  • Understanding complex logic through algorithms can be very difficult.
  • Branching and Looping statements are difficult to show in Algorithms (imp) .

How to Design an Algorithm?

To write an algorithm, the following things are needed as a pre-requisite: 

  • The problem that is to be solved by this algorithm i.e. clear problem definition.
  • The constraints of the problem must be considered while solving the problem.
  • The input to be taken to solve the problem.
  • The output is to be expected when the problem is solved.
  • The solution to this problem is within the given constraints.

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.

Step 1: Fulfilling the pre-requisites  

As discussed above, to write an algorithm, its prerequisites must be fulfilled. 

  • The problem that is to be solved by this algorithm : Add 3 numbers and print their sum.
  • The constraints of the problem that must be considered while solving the problem : The numbers must contain only digits and no other characters.
  • The input to be taken to solve the problem: The three numbers to be added.
  • The output to be expected when the problem is solved: The sum of the three numbers taken as the input i.e. a single integer value.
  • The solution to this problem, in the given constraints: The solution consists of adding the 3 numbers. It can be done with the help of the ‘+’ operator, or bit-wise, or any other method.

Step 2: Designing the algorithm

Now let’s design the algorithm with the help of the above pre-requisites:

Algorithm to add 3 numbers and print their sum:  

  • Declare 3 integer variables num1, num2, and num3.
  • Take the three numbers, to be added, as inputs in variables num1, num2, and num3 respectively.
  • Declare an integer variable sum to store the resultant sum of the 3 numbers.
  • Add the 3 numbers and store the result in the variable sum.
  • Print the value of the variable sum

Step 3: Testing the algorithm by implementing it.

To test the algorithm, let’s implement it in C language.

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

  • Declare three variables num1, num2, and num3 to store the three numbers to be added.
  • Declare a variable sum to store the sum of the three numbers.
  • Use the cout statement to prompt the user to enter the first number.
  • Use the cin statement to read the first number and store it in num1.
  • Use the cout statement to prompt the user to enter the second number.
  • Use the cin statement to read the second number and store it in num2.
  • Use the cout statement to prompt the user to enter the third number.
  • Use the cin statement to read and store the third number in num3.
  • Calculate the sum of the three numbers using the + operator and store it in the sum variable.
  • Use the cout statement to print the sum of the three numbers.
  • The main function returns 0, which indicates the successful execution of the program.

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 of adding 3 numbers, the sum can be calculated in many ways:

  • Bit-wise operators

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:

1. Priori Analysis:

“Priori” means “before”. Hence Priori analysis means checking the algorithm before its implementation. In this, the algorithm is checked when it is written in the form of theoretical steps. This Efficiency of an algorithm is measured by assuming that all other factors, for example, processor speed, are constant and have no effect on the implementation. This is done usually by the algorithm designer. This analysis is independent of the type of hardware and language of the compiler. It gives the approximate answers for the complexity of the program.

2. Posterior Analysis:

“Posterior” means “after”. Hence Posterior analysis means checking the algorithm after its implementation. In this, the algorithm is checked by implementing it in any programming language and executing it. This analysis helps to get the actual and real analysis report about correctness(for every possible input/s if it shows/returns correct output or not), space required, time consumed, etc. That is, it is dependent on the language of the compiler and the type of hardware used.

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:

  • Time Factor : Time is measured by counting the number of key operations such as comparisons in the sorting algorithm.
  • Space Factor : Space is measured by counting the maximum memory space required by the algorithm to run/execute.

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:   

  • Fixed Part: This refers to the space that is required by the algorithm. For example, input variables, output variables, program size, etc.
  • Variable Part: This refers to the space that can be different based on the implementation of the algorithm. For example, temporary variables, dynamic memory allocation, recursion stack space, etc. Therefore Space complexity S(P) of any algorithm P is S(P) = C + SP(I) , where C is the fixed part and S(I) is the variable part of the algorithm, which depends on instance characteristic I.

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 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: 

  • Constant time part: Any instruction that is executed just once comes in this part. For example, input, output, if-else, switch, arithmetic operations, etc.

T(P)

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) = 1 + n + n(1 + 1) + 1 = 2 + 3n, which can be said as T(n).

How to express an Algorithm?

  • Natural Language:- Here we express the Algorithm in the natural English language. It is too hard to understand the algorithm from it.
  • Flowchart :- Here we express the Algorithm by making a graphical/pictorial representation of it. It is easier to understand than Natural Language.
  • Pseudo Code :- Here we express the Algorithm in the form of annotations and informative text written in plain English which is very much similar to the real code but as it has no syntax like any of the programming languages, it can’t be compiled or interpreted by the computer. It is the best way to express an algorithm because it can be understood by even a layman with some school-level knowledge.

Please Login to comment...

Similar reads.

  • SUMIF in Google Sheets with formula examples
  • How to Get a Free SSL Certificate
  • Best SSL Certificates Provider in India
  • Elon Musk's xAI releases Grok-2 AI assistant
  • Content Improvement League 2024: From Good To A Great Article

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Join Our Newsletter

Join our subscribers list to get the latest news, updates and special offers directly in your inbox

  • Interview Q & A
  • Python Interview Q & A

[2024] Python Algorithms Interview Questions

Prepare for your python coding interviews with our comprehensive guide on the most common algorithms interview questions. explore essential topics like sorting algorithms, dynamic programming, graph traversal, and more. enhance your problem-solving skills and boost your confidence with practical examples and explanations..

[2024] Python Algorithms Interview Questions

1. What is an algorithm, and why is it important in programming?

2. explain the difference between a list and a tuple in python. when would you use each, 3. what is a sorting algorithm can you describe the bubble sort algorithm, 4. describe the quicksort algorithm and its time complexity., 5. how does the binary search algorithm work what is its time complexity, 6. what is the difference between depth-first search (dfs) and breadth-first search (bfs) algorithms, 7. explain the concept of dynamic programming with an example., 8. what is a greedy algorithm can you provide an example, 9. what are hash tables, and how do they work, 10. describe the concept of recursion. can you provide an example, 11. what is a heap, and how is it used in algorithms, 12. explain the concept of memoization. how is it different from dynamic programming, 13. what is the difference between merge sort and quicksort, 14. what are some common string algorithms in python, 15. describe the concept of a linked list. what are its advantages and disadvantages, 16. how does the a* (a-star) algorithm work what is its primary use, 17. explain the concept of a binary search tree (bst). how do you perform in-order traversal.

  • Traverse the left subtree.
  • Visit the root node.
  • Traverse the right subtree.

18. What is the concept of “Big O” notation, and why is it important?

19. describe the depth-first search (dfs) algorithm. what are its applications, 20. what is a trie (prefix tree), and how is it used, 21. explain the concept of dijkstra’s algorithm. what is it used for, 22. what is a balanced binary tree provide an example., 23. describe the concept of a "backtracking" algorithm with an example., 24. what is the difference between an iterative and a recursive algorithm.

  • Iterative Algorithm : Uses loops (e.g., for, while) to repeat steps until a condition is met. It is generally more space-efficient.
  • Recursive Algorithm : The function calls itself to solve sub-problems until a base case is reached. It can be more elegant but may use more memory due to function call stack overhead.

25. Explain the concept of the Knapsack problem and how it can be solved.

26. what is a graph, and what are some common ways to represent it, 27. describe the concept of a “hash function” and its use in hash tables., 28. what is the floyd-warshall algorithm used for, 29. explain the concept of the "divide and conquer" algorithm paradigm with an example., 30. what is a permutation, and how can you generate all permutations of a string in python, 31. describe the concept of the “union-find” data structure. what is it used for, 32. what is the difference between bfs and dfs in terms of implementation, 33. explain how you can use python to solve the problem of finding the longest increasing subsequence in an array., 34. what is a “graph traversal” algorithm, and why is it important, 35. describe the concept of “greedy algorithms” with an example., 36. what is the difference between a linear search and a binary search, 37. what is the concept of “dynamic programming” and how is it different from “divide and conquer”, 38. explain the concept of “topological sorting” and its applications., 39. what is a “segment tree” and what problems does it solve, 40. describe the “kadane’s algorithm” and its use case..

  • Python algorithms interview questions
  • Python coding interview questions
  • algorithm interview questions
  • Python programming
  • coding interview preparation
  • data structures and algorithms
  • Python algorithm examples
  • technical interview questions
  • coding interview tips

example problem solving algorithms

Ashwini Ghugarkar

Related Posts

[2024] Python Coding Challenges for Interviews

[2024] Python Coding Challenges for Interviews

[2024] Common Python Interview Questions

[2024] Common Python Interview Questions

[2024] Python Object-Oriented Programming Interview Questions

[2024] Python Object-Oriented Programming Interview Questions

Popular posts.

How to Install Red Hat Enterprise Linux (RHEL) 9 ? RHEL 9 Installation Step by Step with Screenshots.

How to Install Red Hat Enterprise Linux (RHEL) 9 ? RHEL...

Aayushi   May 18, 2022  12146

Get 50% Discount on Azure Certification Exam Voucher AZ 900 | AZ 104 | AZ 305 | AZ 400 | AZ 500 | AZ 204

Get 50% Discount on Azure Certification Exam Voucher AZ...

Aayushi   Oct 15, 2022  9584

50% Discount on CKA, CKAD and CKS  Certification 2023 | Kubernetes CKA, CKAD and CKS Exam Discount Voucher

50% Discount on CKA, CKAD and CKS Certification 2023 |...

Aayushi   Oct 11, 2022  9437

What is Linux Operating System and its Evolution and Future

What is Linux Operating System and its Evolution and Fu...

Aayushi   May 3, 2020  7504

50% Discount on Cisco( New CCNA & CCNP) Certification fee | Cisco Exam Discount Voucher

50% Discount on Cisco( New CCNA & CCNP) Certification f...

Aayushi   Feb 25, 2021  7119

Know Everything about RHCSA (Red Hat Certified System Administrator)  Training and Certification Ex200v9

Know Everything about RHCSA (Red Hat Certified System A...

Aayushi   Sep 15, 2022  1486

How to Install Red Hat Enterprise Linux (RHEL) 9 ? RHEL 9 Installation Step by Step with Screenshots.

Red Hat Remote Individual Certification Exams of RHCSA,...

Aayushi   May 22, 2020  2666

Why is Certified Ethical Hacker (CEH v12) So Popular Certification Exam in the Field of Cyber Security?

Why is Certified Ethical Hacker (CEH v12) So Popular Ce...

Aayushi   May 21, 2020  3399

What is kubernetes and Containers? Why is So Popular?

What is kubernetes and Containers? Why is So Popular?

Aayushi   May 15, 2020  2096

  • Networking (5)
  • Security (121)
  • Interview Q & A (245)
  • Python Interview Q & A (13)
  • Common Interview Q & A (16)
  • Cloud Admin Interview Q & A (39)
  • Linux System Admin Interview Q & A (14)
  • Networking Interview Q & A (1)
  • Penetration Testing Interview Q & A (0)
  • WAPT Interview Q & A (0)
  • VAPT Interview Q & A (50)
  • Ethical Hacking Interview Q & A (76)
  • Study Material (2)
  • IT Exams (39)
  • Red Hat Certification (5)
  • AWS Certification (1)
  • Cyber Security Certification (3)

Random Posts

fixer

A Step-by-Step Guide to prepare for Red Hat certification exams

Ethical Hacker Resume Samples for Fresher | Download Sample CV in Docs and pdf File

Ethical Hacker Resume Samples for Fresher | Download Sample CV in Docs...

[2024] CCNA Interview Questions on QoS

[2024] CCNA Interview Questions on QoS

[2024] Linux System Admin Interview Questions for DevOps Roles

[2024] Linux System Admin Interview Questions for DevOps Roles

[2024] CCNA Interview Questions on IPv6

[2024] CCNA Interview Questions on IPv6

  • Aircrack-ng
  • Kubernetes administrator exam
  • AWS cloud admin
  • VAPT interview tips
  • report cybercrime online India
  • EIGRP routing protocol
  • cloud governance tools
  • NAT in networking
  • Docker plugins
  • Cloud Native Development interview questions
  • network traffic analysis
  • interview answers
  • API throttling

Information

  • Author Services

Initiatives

You are accessing a machine-readable page. In order to be human-readable, please install an RSS reader.

All articles published by MDPI are made immediately available worldwide under an open access license. No special permission is required to reuse all or part of the article published by MDPI, including figures and tables. For articles published under an open access Creative Common CC BY license, any part of the article may be reused without permission provided that the original article is clearly cited. For more information, please refer to https://www.mdpi.com/openaccess .

Feature papers represent the most advanced research with significant potential for high impact in the field. A Feature Paper should be a substantial original Article that involves several techniques or approaches, provides an outlook for future research directions and describes possible research applications.

Feature papers are submitted upon individual invitation or recommendation by the scientific editors and must receive positive feedback from the reviewers.

Editor’s Choice articles are based on recommendations by the scientific editors of MDPI journals from around the world. Editors select a small number of articles recently published in the journal that they believe will be particularly interesting to readers, or important in the respective research area. The aim is to provide a snapshot of some of the most exciting work published in the various research areas of the journal.

Original Submission Date Received: .

  • Active Journals
  • Find a Journal
  • Proceedings Series
  • For Authors
  • For Reviewers
  • For Editors
  • For Librarians
  • For Publishers
  • For Societies
  • For Conference Organizers
  • Open Access Policy
  • Institutional Open Access Program
  • Special Issues Guidelines
  • Editorial Process
  • Research and Publication Ethics
  • Article Processing Charges
  • Testimonials
  • Preprints.org
  • SciProfiles
  • Encyclopedia

symmetry-logo

Article Menu

example problem solving algorithms

  • Subscribe SciFeed
  • Recommended Articles
  • Google Scholar
  • on Google Scholar
  • Table of Contents

Find support for a specific problem in the support section of our website.

Please let us know what you think of our products and services.

Visit our dedicated information section to learn more about MDPI.

JSmol Viewer

Solving the qly least squares problem of dual quaternion matrix equation based on stp of dual quaternion matrices.

example problem solving algorithms

1. Introduction

2. preliminaries, 2.1. the relevant knowledge of dual vectors (matrices) and dual quaternion vectors (matrices).

  • ( 1 ) ψ ( A + B ) = ψ ( A ) + ψ ( B ) ; ψ ( λ A ) = λ ψ ( A ) ; ψ ( A C ) = ψ ( A ) ψ ( C ) .
  • ( 2 ) ψ ( A + B ) c = ψ ( A ) c + ψ ( B ) c ; ψ ( λ A ) c = λ ψ ( A ) c ; ψ ( A C ) c = ψ ( A ) ψ ( C ) c .
  • ( 3 ) ψ ( A + B ) r = ψ ( A ) r + ψ ( B ) r ; ψ ( λ A ) r = λ ψ ( A ) r ; ψ ( A C ) r = ψ ( A ) r ψ ( C ) .

2.2. The STP of Dual Quaternion Matrices

  • ( a ) A ⋈ ( a B + b C ) = a A ⋈ B + b A ⋈ C , ( a A + b B ) ⋈ C = a A ⋈ C + b B ⋈ C ,
  • ( b ) A ⋈ B ⋈ C = A ⋈ B ⋈ C ,
  • ( c ) A ⋈ B H = B H ⋈ A H .
  • ( a ) W [ m , n ] ⋉ x ⋉ y ¯ = y ¯ ⋉ x ¯ ,
  • ( b ) p ⋉ q ¯ ⋉ W [ m , n ] = q ¯ ⋉ p ¯ ,
  • ( c ) W [ m , n ] V r ( A ) = V c ( A ) , W [ n , m ] V c ( A ) = V r ( A ) ,
  • ( d ) x T A ¯ = V r T ( A ¯ ) ⋉ x ¯ , A y ¯ = y H ⋉ V c ( A ¯ ) .

3. Algebraic Solution to Problem 1

4. numerical algorithm and examples.

Calculate the QLY minimal norm least squares Hermitian solution.
  ;
 
1. Fix the form of satisfying Definition 1;
2. Calculate of -representation of dual quaternion Hermitian matrix;
3. Calculate U, V;
4. Calculate ;
5. Calculate the QLY least squares Hermitian solution according to ( ).

5. Discussion

6. conclusions, author contributions, data availability statement, conflicts of interest.

  • Yang, A.T. Analysis of an offset unsymmetric gyroscope with oblique rotor using (3 × 3) matrices with dual-number elements. Eng. Ind. 1969 , 91 , 535–541. [ Google Scholar ] [ CrossRef ]
  • Veldkamp, G.R. On the use of dual numbers, vectors and matrices in instantaneous, spatial kinematics. Mech. Mach. Theory 1976 , 11 , 141–156. [ Google Scholar ] [ CrossRef ]
  • Angeles, J. The application of dual algebra to kinematic analysis. In Computational Methods in Mechanical Systems: Mechanism Analysis, Synthesis, and Optimization ; Springer: Berlin/Heidelberg, Germany, 1998; pp. 3–32. [ Google Scholar ] [ CrossRef ]
  • Han, D.; Wei, Q.; Li, Z.; Sun, W. Control of oriented mechanical systems: A method based on dual quater-nion. IFAC Proc. Vol. 2008 , 41 , 3836–3841. [ Google Scholar ] [ CrossRef ]
  • Fu, Z.; Pan, J.; Spyrakos-Papastavridis, E.; Chen, X.; Li, M. A dual quaternion-based approach for coordi-nate calibration of dual robots in collaborative motion. IEEE Robot. Autom. Lett. 2020 , 5 , 4086–4093. [ Google Scholar ] [ CrossRef ]
  • Dooley, J.R.; McCarthy, J.M. Spatial rigid body dynamics using dual quaternion components. In Proceedings of the 1991 IEEE International Conference on Robotics and Automation, Sacramento, CA, USA, 9–11 April 1991; IEEE: Piscataway, NJ, USA, 1991; pp. 90–95. [ Google Scholar ] [ CrossRef ]
  • Bultmann, S.; Li, K.; Hanebeck, U.D. Stereo visual SLAM based on unscented dual quaternion filtering. In Proceedings of the 2019 22th International Conference on Information Fusion (FUSION), Ottawa, ON, Canada, 2–5 July 2019. [ Google Scholar ] [ CrossRef ]
  • Leclercq, G.; Lefèvre, P.; Blohm, G. 3D kinematics using dual quaternions: Theory and applications in neu-roscience. Front. Behav. Neurosci. 2013 , 7 , 7. [ Google Scholar ] [ CrossRef ] [ PubMed ]
  • Brambley, G.; Kim, J. Unit dual quaternion-based pose optimisation for visual runway observations. IET Cyber-Syst. Robot. 2020 , 2 , 181–189. [ Google Scholar ] [ CrossRef ]
  • Qi, L.; Luo, Z. Eigenvalues and singular values of dual quaternion matrices. Pac. J. Optim. 2023 , 19 , 257–272. [ Google Scholar ]
  • Ling, C.; Qi, L.; Yan, H. Minimax principle for eigenvalues of dual quaternion Hermitian matrices and generalized inverses of dual quaternion matrices. Numer. Funct. Anal. Optim. 2023 , 44 , 1371–1394. [ Google Scholar ] [ CrossRef ]
  • Cui, C.; Qi, L. A power method for computing the dominant eigenvalue of a dual quaternion Hermitian ma-trix. J. Sci. Comput. 2024 , 100 , 21. [ Google Scholar ] [ CrossRef ]
  • Zhang, Y.; Jiang, D.; Wang, J. A recurrent neural network for solving Sylvester equation with time-varying coefficients. IEEE Trans. Neural Netw. 2002 , 13 , 1053–1063. [ Google Scholar ] [ CrossRef ]
  • Bouhamidi, A.; Jbilou, K. Sylvester Tikhonov-regularization methods in image restoration. J. Comput. Appl. Math. 2007 , 206 , 86–98. [ Google Scholar ] [ CrossRef ]
  • Ding, W.; Li, Y.; Wang, D. A real method for solving quaternion matrix equation X − A X ^ B = C based on semi-tensor product of matrices. Adv. Appl. Clifford Algebr. 2021 , 31 , 78. [ Google Scholar ] [ CrossRef ]
  • Jiang, T.; Ling, S. On a solution of the quaternion matrix equation and its applications. Adv. Appl. Clifford Algebr. 2013 , 23 , 689–699. [ Google Scholar ] [ CrossRef ]
  • Li, Y.; Ding, W.; Zhao, X.; Wei, A.; Zhao, J. Direct methods of solving quaternion matrix equation based on STP. In Matrix and Operator Equations and Applications ; Springer Nature: Cham, Switzerland, 2023; pp. 185–209. [ Google Scholar ] [ CrossRef ]
  • Zhang, F.; Wei, M.; Li, Y.; Zhao, J. Special least squares solutions of the quaternion matrix equation AX = B with applications. Appl. Math. Comput. 2015 , 270 , 425–433. [ Google Scholar ] [ CrossRef ]
  • Jäntschi, L. Eigenproblem Basics and Algorithms. Symmetry 2023 , 15 , 2046. [ Google Scholar ] [ CrossRef ]
  • Chen, Y.; Wang, Q.W.; Xie, L.M. Dual quaternion matrix equation AXB = C with applications. Symmetry 2024 , 16 , 287. [ Google Scholar ] [ CrossRef ]
  • Zeng, M.; Yuan, Y. The solution of the dual matrix equation A T X + X T A = D . Kuwait J. Sci. 2024 , 51 , 100141. [ Google Scholar ] [ CrossRef ]
  • Qi, L.; Ling, C.; Yan, H. Dual quaternions and dual quaternion vectors. Commun. Appl. Math. Comput. 2022 , 4 , 1494–1508. [ Google Scholar ] [ CrossRef ]
  • Wang, H.; Cui, C.; Wei, Y. The QLY least-squares and the QLY least-squares minimal-norm of linear dual least squares problems. Linear Multilinear A 2024 , 72 , 1985–2002. [ Google Scholar ] [ CrossRef ]
  • Demir, S. Matrix realization of dual quaternionic electromagnetism. Cent. Eur. J. Phys. 2007 , 5 , 487–506. [ Google Scholar ] [ CrossRef ]
  • Cheng, D.; Qi, H.; Zhao, Y. An Introduction to Semi-Tensor Product of Matrices and Its Applications ; World Scientific: Singapore, 2012. [ Google Scholar ]
  • Fan, X.; Li, Y.; Ding, W.; Zhao, J. Semi-tensor product of quaternion matrices and its application. Math. Methods Appl. Sci. 2023 , 46 , 6450–6462. [ Google Scholar ] [ CrossRef ]
  • Zhang, W.H.; Chen, B.S. H-representation and applications to generalized Lyapunov equations and linear stochastic systems. IEEE Trans. Autom. Control 2012 , 57 , 3009–3022. [ Google Scholar ] [ CrossRef ]
The statements, opinions and data contained in all publications are solely those of the individual author(s) and contributor(s) and not of MDPI and/or the editor(s). MDPI and/or the editor(s) disclaim responsibility for any injury to people or property resulting from any ideas, methods, instructions or products referred to in the content.

Share and Cite

Tao, R.; Li, Y.; Zhang, M.; Liu, X.; Wei, M. Solving the QLY Least Squares Problem of Dual Quaternion Matrix Equation Based on STP of Dual Quaternion Matrices. Symmetry 2024 , 16 , 1117. https://doi.org/10.3390/sym16091117

Tao R, Li Y, Zhang M, Liu X, Wei M. Solving the QLY Least Squares Problem of Dual Quaternion Matrix Equation Based on STP of Dual Quaternion Matrices. Symmetry . 2024; 16(9):1117. https://doi.org/10.3390/sym16091117

Tao, Ruyu, Ying Li, Mingcui Zhang, Xiaochen Liu, and Musheng Wei. 2024. "Solving the QLY Least Squares Problem of Dual Quaternion Matrix Equation Based on STP of Dual Quaternion Matrices" Symmetry 16, no. 9: 1117. https://doi.org/10.3390/sym16091117

Article Metrics

Article access statistics, further information, mdpi initiatives, follow mdpi.

MDPI

Subscribe to receive issue release notifications and newsletters from MDPI journals

IMAGES

  1. problem solving algorithm and flowchart

    example problem solving algorithms

  2. PPT

    example problem solving algorithms

  3. What is Problem Solving Algorithm?, 4 Steps, Representation

    example problem solving algorithms

  4. PPT

    example problem solving algorithms

  5. Algorithmic Problem Solving

    example problem solving algorithms

  6. algorithm problem solving strategies

    example problem solving algorithms

COMMENTS

  1. How to Use Algorithms to Solve Problems?

    End - End the execution. 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.

  2. Algorithms Tutorial

    Algorithms Tutorial. Algorithm is a step-by-step procedure for solving a problem or accomplishing a task. In the context of data structures and algorithms, it is a set of well-defined instructions for performing a specific computational task. Algorithms are fundamental to computer science and play a very important role in designing efficient ...

  3. PDF Principles of Algorithmic Problem Solving

    by Euler, algorithmic problem solving has been a popular intellectual pursuit during the last few thousand years. For a long time, it was a purely mathemati-cal endeavor with algorithms meant to be executed by hand. During the recent decades algorithmic problem solving has evolved. What was mainly a topic of

  4. Khan Academy

    Learn how to design and analyze algorithms for solving various problems in computer science, with articles, visualizations, quizzes, and coding challenges.

  5. How to Solve an Algorithm Problem?

    2) Break the problem down. Here is a step-by-step explanation of the algorithm in plain English: Convert all uppercase letters in the string to lowercase. This is done so that the case of the letters in the string does not affect the outcome of the comparison. Remove all non-alphanumeric characters from the string.

  6. How to use algorithms to solve everyday problems

    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.

  7. 4. Problem Solving and Algorithms

    An algorithm is a plan for solving a problem, but plans come in several levels of detail. It's usually better to start with a high-level algorithm that includes the major part of a solution, but leaves the details until later. ... For example, an algorithm that computes the area of a circle having radius 5.2 meters (formula π*5.2 2) solves a ...

  8. Chapter 3 Solving Problems by Searching

    3.3 Search Algorithms. A search algorithm takes a search problem as input and returns a solution, or an indication of failure. We consider algorithms that superimpose a search tree over the state-space graph, forming various paths from the initial state, trying to find a path that reaches a goal state.

  9. Introduction to Algorithms: What Every Beginner Should Know

    3. Efficiency. Efficiency is a critical consideration in algorithm design. It's about finding the most optimal way to solve a problem, which often involves minimizing the consumption of time and resources. 4. Scalability. Algorithms should be designed to handle input data of varying sizes efficiently.

  10. What is an Algorithm?

    In computer programming terms, an algorithm is a set of well-defined instructions to solve a particular problem. It takes a set of input (s) and produces the desired output. For example, An algorithm to add two numbers: Take two number inputs. Add numbers using the + operator. Display the result.

  11. What Is an Algorithm?

    An algorithm is a sequence of instructions that a computer must perform to solve a well-defined problem. It essentially defines what the computer needs to do and how to do it. Algorithms can instruct a computer how to perform a calculation, process data, or make a decision. The best way to understand an algorithm is to think of it as a recipe ...

  12. Understanding Algorithms: The Key to Problem-Solving Mastery

    At its core, an algorithm is a systematic, step-by-step procedure or set of rules designed to solve a problem or perform a specific task. It provides clear instructions that, when followed meticulously, lead to the desired outcome. Consider an algorithm to be akin to a recipe for your favorite dish.

  13. 1: Algorithmic Problem Solving

    1.1: Activity 1 - Introduction to Algorithms and Problem Solving. In this learning activity section, the learner will be introduced to algorithms and how to write algorithms to solve tasks faced by learners or everyday problems. Examples of the algorithm are also provided with a specific application to everyday problems that the learner is ...

  14. Algorithm Practice Question for Beginners

    Greedy algorithm and divide and conquer algorithm are two common algorithmic paradigms used to solve problems. The main difference between them lies in their approach to solving problems. Greedy Algorithm:The greedy algorithm is an algorithmic paradigm that follows the problem-solving heuristic of making the locally optimal choice at each stage wit

  15. Khan Academy

    If this problem persists, tell us. Our mission is to provide a free, world-class education to anyone, anywhere. Khan Academy is a 501(c)(3) nonprofit organization. Donate or volunteer today! Site Navigation. About. News; Impact; Our team; Our interns; Our content specialists; Our leadership; Our supporters; Our contributors; Our finances;

  16. Algorithms

    An algorithm is a procedure that takes in input, follows a certain set of steps, and then produces an output. Oftentimes, the algorithm defines a desired relationship between the input and output. For example, if the problem that we are trying to solve is sorting a hand of cards, the problem might be defined as follows: This last part is very important, it&#x27;s the meat and substance of the ...

  17. What is a Greedy Algorithm? Examples of Greedy Algorithms

    Greedy algorithms are a straightforward approach to solving optimization problems, returning a minimum or maximum value. This article explained some examples of greedy algorithms and the approach to tackling each problem. By understanding how a greedy algorithm problems works you can better understand dynamic programming.

  18. Solving the Travelling Salesman Problem Using a Genetic Algorithm

    A Genetic Algorithm, GA, is a machine learning technique that is modelled on biological evolution. It is a guided random search algorithm that can explore a large solution space very efficiently. A GA involves building a population of 'chromosomes' which act as potential solutions to the problem we are attempting to solve.

  19. Definition, Types, Complexity and Examples of Algorithm

    Algorithms are used to solve problems or automate tasks in a systematic and efficient manner. They are a set of instructions or rules that guide the computer or software in performing a particular task or solving a problem. ... Example 1: Write an algorithm to find the maximum of all the elements present in the array. Follow the algorithm ...

  20. 6 Real World Algorithm Examples for Students

    6 Examples of Real-World Algorithms. Whether algorithms are used in places that aren't at all surprising, like Google, or in a manual activity that is more unexpected, like brushing your teeth, algorithms play a role in the human experience every single day, Guyon goes on to explain. 1. Sorting Papers. Imagine a teacher sorting their students ...

  21. 1.1: Activity 1

    By using an example, describe how the concept of algorithms can be well presented to a group of students being introduced to it. 1.1: Activity 1 - Introduction to Algorithms and Problem Solving is shared under a CC BY-SA license and was authored, remixed, and/or curated by LibreTexts. In this learning activity section, the learner will be ...

  22. Solve Algorithms

    Join over 23 million developers in solving code challenges on HackerRank, one of the best ways to prepare for programming interviews.

  23. What Are Algorithms? A Guide to Algorithms for Children

    An algorithm definition is as simple as a set of step-by-step procedures or a list of rules to follow for completing a specific task or solving a particular problem. Even though the word 'algorithm' was first coined in the 9th century, they are all around us until today. Common algorithm examples include the recipe for baking a cake, the ...

  24. What is Algorithm

    Example: Consider the example to add three numbers and print the sum. Step 1: Fulfilling the pre-requisites . As discussed above, to write an algorithm, its prerequisites must be fulfilled. The problem that is to be solved by this algorithm: Add 3 numbers and print their sum.; The constraints of the problem that must be considered while solving the problem: The numbers must contain only digits ...

  25. [2024] Python Algorithms Interview Questions

    They are important for solving problems like finding the shortest path, checking connectivity, and performing operations on graphs. 35. Describe the concept of "Greedy Algorithms" with an example. Greedy algorithms build up a solution piece by piece, always choosing the next piece that offers the most immediate benefit.

  26. Solving the QLY Least Squares Problem of Dual Quaternion Matrix

    In Example 1, we show a numerical example to solve the Hermitian solution for the QLY minimal norm least squares problem of dual quaternion matrix Equation , which has a special structure. For the solution without a special structure, we only need to omit the H D in Algorithm 1 according to the GH -representation, and then we can obtain the ...