• DSA Tutorial
  • Data Structures
  • Linked List
  • Dynamic Programming
  • Binary Tree
  • Binary Search Tree
  • Divide & Conquer
  • Mathematical
  • Backtracking
  • Branch and Bound
  • Pattern Searching
  • Ternary Search for Competitive Programming
  • Interactive Problems in Competitive Programming | Set 2
  • How An Online Judge Works And How To Avoid Time Limit Exceeded Problem?
  • A Quick Guide on DSA and Competitive Coding in Java
  • Competitive Programming - A Complete Guide
  • 25 Essential Concepts for Competitive Programming
  • What to do at the time of Wrong Answer (WA)?
  • Competitive Programming: Conquering a given problem
  • Test Case Generation | Set 5 (Generating random Sorted Arrays and Palindromes)
  • Count triplets with specific property
  • Minimize cost to sort Binary String by swapping pairs or reversing prefix at most once
  • Competitive Programming (CP) Handbook with Complete Roadmap
  • Test Case Generation | Set 1 (Random Numbers, Arrays and Matrices)
  • Distinct elements in subarray using Mo's Algorithm
  • Test Case Generation | Set 4 (Random directed / undirected weighted and unweighted Graphs)
  • Find if it is possible to reach the end through given transitions
  • Importance of Testing In Competitive Programming
  • What are Ad Hoc Problems in Competitive Programming?
  • Most Popular Weekly Coding Contest Platforms

How To Approach A Coding Problem ?

Solving a DSA (Data Structures and Algorithms) Problem is quite tough. In This article, we help you not only solve the problem but actually understand it, It’s not about just solving a problem it’s about understanding the problem. we will help to solve DSA problems on websites like Leetcode, CodeChef, Codeforces, and Geeksforgeeks. the importance of solving a problem is not just limited to job interviews or solve problems on online platform, its about develop a problem solving abilities which is make your prefrontal cortex strong, sharp and prepared it to solve complex problem in future, not only DSA problems also in life.

These steps you need to follow while solving a problem:

– Understand the question, read it 2-3 times. – Take an estimate of the required complexity. – find, edge cases based on the constraints. – find a brute-force solution. ensure it will pass. – Optimize code, ensure, and repeat this step. – Dry-run your solution(pen& paper) on the test cases and edge cases. – Code it and test it with the test cases and edge cases. – Submit solution. Debug it and fix it, if the solution does not work.

How-to-Approach-a-Coding-Problem

Understand The Question

firstly read it 2-3 times, It doesn’t matter if you have seen the question in the past or not, read the question several times and understand it completely. Now, think about the question and analyze it carefully. Sometimes we read a few lines and assume the rest of the things on our own but a slight change in your question can change a lot of things in your code so be careful about that. Now take a paper and write down everything. What is given (input) and what you need to find out (output)? While going through the problem you need to ask a few questions yourself…

  • Did you understand the problem fully?
  • Would you be able to explain this question to someone else?
  • What and how many inputs are required?
  • What would be the output for those inputs
  • Do you need to separate out some modules or parts from the problem?
  • Do you have enough information to solve that question? If not then read the question again or clear it to the interviewer.

                Estimate of the required complexity

Look at the constraints and time limit. This should give you a rough idea of the expected time and space complexity. Use this step to reject the solutions that will not pass the limits. With some practice, you will be able to get an estimate within seconds of glancing at the constraints and limits.

              Find, edge cases 

In most problems, you would be provided with sample input and output with which you can test your solution. These tests would most likely not contain the edge cases. Edge cases are the boundary cases that might need additional handling. Before jumping on to any solution, write down the edge cases that your solution should work on. When you try to understand the problem take some sample inputs and try to analyze the output. Taking some sample inputs will help you to understand the problem in a better way. You will also get clarity that how many cases your code can handle and what all can be the possible output or output range.

Constraints 

0 <= T <= 100

1 <= N <= 1000

-1000 <= value of element <= 1000

Find a brute-force Solution

A brute-force solution for a DSA (Data Structure and Algorithm) problem involves exhaustively checking all possible solutions until the correct one is found. This method is typically very time-consuming and not efficient, but can be useful for small-scale problems or as a way to verify the correctness of a more optimized solution. One example of a problem that could be solved using a brute-force approach is finding the shortest path in a graph. The algorithm would check every possible path until the shortest one is found.

Break Down The Problem

When you see a coding question that is complex or big, instead of being afraid and getting confused that how to solve that question, break down the problem into smaller chunks and then try to solve each part of the problem. Below are some steps you should follow in order to solve the complex coding questions… 

  • Make a flow chart or a UML for the problem at hand.
  • Divide the problem into sub-problems or smaller chunks.
  • Solve the subproblems. Make independent functions for each subproblem.
  • Connect the solutions of each subproblem by calling them in the required order, or as necessary.
  • Wherever it’s required use classes and objects while handling questions (for real-world problems like management systems, etc.)

Optimize your Code

Always try to improve your code. Look back, analyze it once again and try to find a better or alternate solution. We have mentioned earlier that you should always try to write the right amount of good code so always look for the alternate solution which is more efficient than the previous one. Writing the correct solution to your problem is not the final thing you should do. Explore the problem completely with all possible solutions and then write down the most efficient or optimized solution for your code. So once you are done with writing the solution for your code below are some questions you should ask yourself. 

Optimizing a solution in DSA (Data Structure and Algorithm) refers to improving the efficiency of an algorithm by reducing the time and/or space complexity. This can be done by using techniques such as dynamic programming, greedy algorithms, divide and conquer, backtracking, or using more efficient data structures.

It’s important to note that the optimization process is not always straightforward and it can be highly dependent on the specific problem and constraints. The optimization process usually starts with a brute force approach, and then various techniques will be applied to make the algorithm more efficient. The optimization process will often require a trade-off between time and space complexity.

Also, measuring and analyzing the performance of the algorithm is an essential step in the optimization process. The use of mathematical notation and analysis tools like Big O notation and complexity analysis, can help to understand the performance of an algorithm and decide which one is the best.

  • Does this code run for every possible input including the edge cases.
  • Is there an alternate solution for the same problem?
  • Is the code efficient? Can it be more efficient or can the performance be improved?
  • How else can you make the code more readable?
  • Are there any more extra steps or functions you can take out?
  • Is there any repetition in your code? Take it out.

Below is the alternate solution for the same problem of the array which returns even numbers… 

          Dry-run your solution

Dry-running a solution on test cases and edge cases involves manually going through the steps of the algorithm with sample inputs and verifying that the output is correct. This process can help to identify any bugs or errors in the code, as well as ensure that the algorithm is correctly handling all possible inputs, including edge cases.

When dry-running your solution, it’s important to consider both the expected test cases and any unexpected edge cases that may arise. Edge cases are inputs that are at the boundaries of the problem’s constraints, for example, the maximum or minimum values.

To dry-run the solution, you will need to:

  • Write down the sample test case inputs and expected outputs.
  • Go through the steps of the algorithm manually, using the test case inputs.
  • Compare the output of the algorithm to the expected output, to ensure the solution is correct.
  • Repeat the process for each test case and edge case.
  • Dry-running your solution on test cases and edge cases can help you to identify any issues with your algorithm, and make any necessary adjustments before running the code on a computer.

             Code & Test it On Edge Cases

After dry-running your solution and verifying that it is right, the next step is to code it and test it using the test cases and edge cases.

To code the solution, you will need to:

  •  write the code for the algorithm.
  • Make sure to include any necessary data structures and methods.
  • Test the code with sample inputs, including the test cases and edge cases that were used during the dry-run.
  • When testing the code, it’s important to not only check for the expected outputs, but also for any unexpected behavior or errors. Testing with edge cases is especially important as it can reveal bugs or errors that might not be present in other test cases.

It’s also a good practice to test the code with additional test cases and edge cases, to further ensure the correctness and robustness of the solution.

Once the code has been tested and all the bugs have been fixed, you can submit it.

 Submit solution

After coding and testing the solution on the sample test cases, the next step is to submit it, usually to a platform for review or for a contest.

The submission process can depending on the platform, but basically it involves submitting the code and any necessary documentation. After the submission, the solution is usually reviewed by other participants or judges, and feedback is provided on whether the solution is correct or if there are any errors. If the solution is wrong or does not work as expected, the next step is to debug and fix it. Debugging is the process of identifying and resolving errors in the code. This can involve using tools such as a debugger, print statements, or logging to find the source of the problem.

Once the error has been identified, the next step is to fix it. This can involve making changes to the code, data structures, or algorithms used. Once the changes have been made, it’s important to test the solution again to ensure that the error has been resolved and that the solution is correct.

If the solution is correct, you can submit it again or move on to other problems.

It’s important to note that the debugging and fixing process can be an iterative one and it may take several iterations to get the solution working correctly.

Please Login to comment...

Similar reads.

author

  • Competitive Programming

advertisewithusBannerImg

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Tutorial Playlist

Programming tutorial, your guide to the best backend languages for 2024, an ultimate guide that helps you to start learn coding 2024, what is backend development: the ultimate guide for beginners, all you need to know for choosing the first programming language to learn, here’s all you need to know about coding, decoding, and reasoning with examples, understanding what is xml: the best guide to xml and its concepts., an ultimate guide to learn the importance of low-code and no-code development, top frontend languages that you should know about, top 75+ frontend developer interview questions and answers, the ultimate guide to learn typescript generics, the most comprehensive guide for beginners to know ‘what is typescript’.

The Ultimate Guide on Introduction to Competitive Programming

Top 60+ TCS NQT Interview Questions and Answers for 2024

Most commonly asked logical reasoning questions in an aptitude test, everything you need to know about advanced typescript concepts, an absolute guide to build c hello world program, a one-stop solution guide to learn how to create a game in unity, what is nat significance of nat for translating ip addresses in the network model, data science vs software engineering: key differences, a real-time chat application typescript project using node.js as a server, what is raspberry pi here’s the best guide to get started, what is arduino here’s the best beginners guide to get started, arduino vs. raspberry pi: which is the better board, the perfect guide for all you need to learn about mean stack, software developer resume: a comprehensive guide, here’s everything all you need to know about the programming roadmap, an ultimate guide that helps you to develop and improve problem solving in programming, the top 10 awesome arduino projects of all time, roles of product managers, pyspark rdd: everything you need to know about pyspark rdd, wipro interview questions and answers that you should know before going for an interview, how to use typescript with nodejs: the ultimate guide, what is rust programming language why is it so popular, software terminologies, an ultimate guide that helps you to develop and improve problem solving in programming.

Lesson 27 of 34 By Hemant Deshpande

An Ultimate Guide That Helps You to Develop and Improve Problem Solving in Programming

Table of Contents

Coding and Programming skills hold a significant and critical role in implementing and developing various technologies and software. They add more value to the future and development. These programming and coding skills are essential for every person to improve problem solving skills. So, we brought you this article to help you learn and know the importance of these skills in the future. 

Want a Top Software Development Job? Start Here!

Want a Top Software Development Job? Start Here!

Topics covered in this problem solving in programming article are:

  • What is Problem Solving in Programming? 
  • Problem Solving skills in Programming
  • How does it impact your career ?
  • Steps involved in Problem Solving
  • Steps to improve Problem Solving in programming

What is Problem Solving in Programming?

Computers are used to solve various problems in day-to-day life. Problem Solving is an essential skill that helps to solve problems in programming. There are specific steps to be carried out to solve problems in computer programming, and the success depends on how correctly and precisely we define a problem. This involves designing, identifying and implementing problems using certain steps to develop a computer.

When we know what exactly problem solving in programming is, let us learn how it impacts your career growth.

How Does It Impact Your Career?

Many companies look for candidates with excellent problem solving skills. These skills help people manage the work and make candidates put more effort into the work, which results in finding solutions for complex problems in unexpected situations. These skills also help to identify quick solutions when they arise and are identified. 

People with great problem solving skills also possess more thinking and analytical skills, which makes them much more successful and confident in their career and able to work in any kind of environment. 

The above section gives you an idea of how problem solving in programming impacts your career and growth. Now, let's understand what problem solving skills mean.

Problem Solving Skills in Programming

Solving a question that is related to computers is more complicated than finding the solutions for other questions. It requires excellent knowledge and much thinking power. Problem solving in programming skills is much needed for a person and holds a major advantage. For every question, there are specific steps to be followed to get a perfect solution. By using those steps, it is possible to find a solution quickly.

The above section is covered with an explanation of problem solving in programming skills. Now let's learn some steps involved in problem solving.

Steps Involved in Problem Solving

Before being ready to solve a problem, there are some steps and procedures to be followed to find the solution. Let's have a look at them in this problem solving in programming article.

Basically, they are divided into four categories:

  • Analysing the problem
  • Developing the algorithm
  • Testing and debugging

Analysing the Problem

Every problem has a perfect solution; before we are ready to solve a problem, we must look over the question and understand it. When we know the question, it is easy to find the solution for it. If we are not ready with what we have to solve, then we end up with the question and cannot find the answer as expected. By analysing it, we can figure out the outputs and inputs to be carried out. Thus, when we analyse and are ready with the list, it is easy and helps us find the solution easily. 

Developing the Algorithm

It is required to decide a solution before writing a program. The procedure of representing the solution  in a natural language called an algorithm. We must design, develop and decide the final approach after a number of trials and errors, before actually writing the final code on an algorithm before we write the code. It captures and refines all the aspects of the desired solution.

Once we finalise the algorithm, we must convert the decided algorithm into a code or program using a dedicated programming language that is understandable by the computer to find a desired solution. In this stage, a wide variety of programming languages are used to convert the algorithm into code. 

Testing and Debugging

The designed and developed program undergoes several rigorous tests based on various real-time parameters and the program undergoes various levels of simulations. It must meet the user's requirements, which have to respond with the required time. It should generate all expected outputs to all the possible inputs. The program should also undergo bug fixing and all possible exception handling. If it fails to show the possible results, it should be checked for logical errors.

Industries follow some testing methods like system testing, component testing and acceptance testing while developing complex applications. The errors identified while testing are debugged or rectified and tested again until all errors are removed from the program.

The steps mentioned above are involved in problem solving in programming. Now let's see some more detailed information about the steps to improve problem solving in programming.

Steps to Improve Problem Solving in Programming

Right mindset.

The way to approach problems is the key to improving the skills. To find a solution, a positive mindset helps to solve problems quickly. If you think something is impossible, then it is hard to achieve. When you feel free and focus with a positive attitude, even complex problems will have a perfect solution.

Making Right Decisions

When we need to solve a problem, we must be clear with the solution. The perfect solution helps to get success in a shorter period. Making the right decisions in the right situation helps to find the perfect solution quickly and efficiently. These skills also help to get more command over the subject.

Keeping Ideas on Track

Ideas always help much in improving the skills; they also help to gain more knowledge and more command over things. In problem solving situations, these ideas help much and help to develop more skills. Give opportunities for the mind and keep on noting the ideas.

Learning from Feedbacks

A crucial part of learning is from the feedback. Mistakes help you to gain more knowledge and have much growth. When you have a solution for a problem, go for the feedback from the experienced or the professionals. It helps you get success within a shorter period and enables you to find other solutions easily.

Asking Questions

Questions are an incredible part of life. While searching for solutions, there are a lot of questions that arise in our minds. Once you know the question correctly, then you are able to find answers quickly. In coding or programming, we must have a clear idea about the problem. Then, you can find the perfect solution for it. Raising questions can help to understand the problem.

These are a few reasons and tips to improve problem solving in programming skills. Now let's see some major benefits in this article.

  • Problem solving in programming skills helps to gain more knowledge over coding and programming, which is a major benefit.
  • These problem solving skills also help to develop more skills in a person and build a promising career.
  • These skills also help to find the solutions for critical and complex problems in a perfect way.
  • Learning and developing problem solving in programming helps in building a good foundation.
  • Most of the companies are looking for people with good problem solving skills, and these play an important role when it comes to job opportunities 
Don't miss out on the opportunity to become a Certified Professional with Simplilearn's Post Graduate Program in Full Stack Web Development . Enroll Today!

Problem solving in programming skills is important in this modern world; these skills build a great career and hold a great advantage. This article on problem solving in programming provides you with an idea of how it plays a massive role in the present world. In this problem solving in programming article, the skills and the ways to improve more command on problem solving in programming are mentioned and explained in a proper way.

If you are looking to advance in your career. Simplilearn provides training and certification courses on various programming languages - Python , Java , Javascript , and many more. Check out our Post Graduate Program in Full Stack Web Development course that will help you excel in your career.

If you have any questions for us on the problem solving in programming article. Do let us know in the comments section below; we have our experts answer it right away.

Find our Full Stack Developer - MERN Stack Online Bootcamp in top cities:

About the author.

Hemant Deshpande

Hemant Deshpande, PMP has more than 17 years of experience working for various global MNC's. He has more than 10 years of experience in managing large transformation programs for Fortune 500 clients across verticals such as Banking, Finance, Insurance, Healthcare, Telecom and others. During his career he has worked across the geographies - North America, Europe, Middle East, and Asia Pacific. Hemant is an internationally Certified Executive Coach (CCA/ICF Approved) working with corporate leaders. He also provides Management Consulting and Training services. He is passionate about writing and regularly blogs and writes content for top websites. His motto in life - Making a positive difference.

Recommended Resources

Your One-Stop Solution to Understand Coin Change Problem

Your One-Stop Solution to Understand Coin Change Problem

Combating the Global Talent Shortage Through Skill Development Programs

Combating the Global Talent Shortage Through Skill Development Programs

What Is Problem Solving? Steps, Techniques, and Best Practices Explained

What Is Problem Solving? Steps, Techniques, and Best Practices Explained

One Stop Solution to All the Dynamic Programming Problems

One Stop Solution to All the Dynamic Programming Problems

The Ultimate Guide on Introduction to Competitive Programming

The Ultimate Guide to Top Front End and Back End Programming Languages for 2021

  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.
  • All Articles
  • Let's Connect
  • Fundamentals
  • Soft Skills
  • Side Projects

A Guide to Problem-Solving for Software Developers with Examples

If I ask you, out of the blue, what’s the role of a developer, what would you answer? Coding all day? Drinking coffee? Complaining about the management?

To me, a developer is first and foremost a problem solver, simply because solving problem is the most important (and the most difficult) part of our job. After all, even if our code is perfect, clear, performing great, a masterpiece of form and meaning, it’s useless if it doesn’t solve the problem it was meant to solve.

So, let’s dive into problem-solving today. More specifically, we’ll see in this article:

  • How to define a problem, and the difference sometimes made between problem-solving and decision-making.
  • Why some problems should not be solved.
  • The two wide categories of problems you can encounter.
  • Why it’s important to correctly define the problem, and how to do so.
  • How to explore the solution space.
  • Why deferring a problem might be the best decision to make in specific situations.
  • Why reflecting on the whole process afterward can help you in the future.

This article is mostly based on my own experience, even if I apply here some ideas I found in books and papers.

We have our plan. Now, it’s time to dive deep into the difficult, but rewarding, process of problem-solving.

Problem-Solving and Decision-Making

“When I use a word,” Humpty Dumpty said in rather a scornful tone, “it means just what I choose it to mean — neither more nor less.” “The question is,” said Alice, “whether you can make words mean so many different things.” “The question is,” said Humpty Dumpty, “which is to be master — that’s all.” Lewis Caroll Source

Words are ambiguous; they can mean different things for each of us. So let’s first begin to agree on the definition of “problem-solving” here, to be sure we’re on the same page.

Let’s first look at the definition of the word “problem” in a dictionary:

  • According to the American Heritage Dictionary , a problem is “a question to be considered, solved, or answered”.
  • According to the Oxford Learner’s dictionary , a problem is “a thing that is difficult to deal with or to understand”.

In short, in any problem, there is some degree of uncertainty. If you’re certain of the solution, the problem is already solved. Nothing would need to be “considered, solved, or answered”.

Information is useful to reduce this uncertainty. The quantity is often not the most important, but the quality will be decisive. If I tell you that 90% of my readers are extremely intelligent, would it help you to solve a problem in your daily job? I bet it wouldn’t. It’s information nonetheless, but its usefulness for you is close to zero.

This is an extreme example, but it highlights an important point: before collecting any data, define your problem clearly; then, according to the problem, decide what data you need. Yet, many companies out there begin to collect the data and then decide what problem to solve. We’ll come back to that soon in this article.

So, to summarize, a problem is a situation with some degree of uncertainty. Sometimes, this uncertainty needs to be reduced to come up with an appropriate solution, or, at least, a decision to move forward to your specific goal.

Is there a Problem to Solve?

Whenever you (or somebody else) see a problem, you should always ask yourself this simple question first: is it really a problem, and should we solve it now ?

In other words, ask yourself the following questions:

  • Why is this problem important to solve?
  • Would be solving the problem creates some value? What value?
  • What would happen if the problem was not solved?
  • What desired outcome do we expect by solving the problem?

If the problem doesn’t bother anybody and solving it doesn’t create any value, why allocating effort and time to solve it?

It sounds obvious, but it’s an important point nonetheless. More often than not, I see developers heading first in solving problems without asking themselves if they should solve them at the first place.

The most common examples I can think of are useless refactoring. I saw developers refactoring parts of codebases which never change, or is rarely executed at runtime. In the mind of the developer, the code itself is the problem: refactoring is the solution.

I remember a similar case: a developer refactored part of the codebase which was basically never used. We discovered, months later, when we had more and more users using this specific part of the codebase, that the refactoring didn’t really simplify anything. To the contrary; we had to refactor the code again. The first refactoring tried to solve a problem which didn’t exists.

Of course, the developer could argue that the value created is a “cleaner” codebase, but it’s arguable, especially when the code is neither often modified nor used. The value created here is not clear, and it would have been easier if the first refactoring never happened. In this specific situation, I recommend refactoring when you actively change part of the codebase for another reason (implementing a new feature for example).

Whether a problem is worthy to be solved is subjective. It also depends on the problem: if the solution is clear and straightforward, it might be useful to solve it, if the consequences of the solution are also clearly known and the risks are low. Unfortunately, these kinds of problems, in practice, are quite rare.

Types of Problems

I would define here two wide categories of problems: the problems with a (or multiple) clear solution (what the literature call “problem-solving”), and the problems without clear solution (it’s sometimes called “decision-making” instead of “problem-solving”).

In fact, if the problem you’re trying to solve has a clear, accepted answer, it’s very likely it has been solved already. It’s often the case for mechanical, technical problems. For example, let’s say that you need to order a list; you just have to search on the wild Internet how to do so in your programming language of choice, and you’re done! You can ask an “AI” too, or stack overflow, or whatever.

In my experience, most technical problems have one (or multiple) accepted solution. I won’t speak about these kinds of problems at length in this article, since they’re the easiest to solve.

When you’re in front of a problem which has no clear solution (even after doing some research), it’s where things get more complicated. I’d argue that most problems you’ll face, as a software developer, are of this category. Problems which are directly linked to the domain of the company you work with are often specific (because they depend on the domain), and complex.

For example, I’m working for a company providing a learning platform for medical students who want to become doctors, among other services. This context is changing because the real world is changing; medicine is no exception.

Recently, we had to create new data structures for the knowledge we provide; these data structures are directly linked to the domain (medicine) here. But what data structures to create? How can they adapt to the ever-changing environment? How to capture the data in the most meaningful way, with understandable naming for other developers?

Decisions had to be made, and when there are no clear solutions, you need to come up with a couple of hypothesizes. They won’t feel necessary like solutions , but rather decisions to take to move forward toward the desired outcome. It often ends up in compromises, especially if you’re working in a team where the members have different opinions .

Also, architectural decisions have often no clear solutions because they depend, again, on the changing context. How to be sure that an architectural decision is good today and in three months? How can we make the architecture flexible enough to adapt to the blurry future?

As developers, we deal with complex codebases, which are somewhat linked to the even more complex real world. It’s difficult to know beforehand the consequences of our decisions, as well as the benefits, the drawback, and the potential bugs we introduce.

Before jumping into the solution space however, we first need a good detour in the problem space.

Defining the Problem

Correctly stating the problem.

After determining that we indeed have some kind of problem, it’s tempting to try to find a solution directly. Be patient: it’s better to look at the problem more closely first.

If you don’t specify well the problem, you might not solve it entirely. It’s also possible that you end up solving the wrong problem, or the symptoms of a problem, that is, other minor problems created by a root problem. Often, the ideal scenario is to find the root problem, even if you don’t want to tackle it first. In any case, it’s always useful information.

For example, not long ago, our users didn’t find the content they were searching for, using our search functionality on our learning platform.

We could have directly solved the problem by asking the search team to adjust that for us, but this problem was only a symptom. It wasn’t the first time that we had to spend time and energy trying to communicate to the search team what we wanted to fix; the real root problem here was that we didn’t have any ownership of our search results.

The solution: we created a better API communicating with the search team, to be able to adjust ourselves the search results in a more flexible manner.

When looking at a problem, a good first step is to write it down. Don’t do it once; try to find different formulations for the same problem.

Writing is nice (I love it!), but other ways to represent ideas can be really useful too. You can try to draw what you understand from the problem: a drawing, a diagram, or even a picture can help you understand the problem.

From there, you can ask yourself: do you have enough information to take a decision? The answer will be mostly based on the experience of the problem solver, there is no magical formula to be sure that you can and will solve the problem.

You should also try to look at the problem from different angles, to really frame it correctly. The best way to do so is to solve problems as a team.

Solving Problems in a Team

Trying to describe and think about a problem is a great beginning, but it’s even better if you do it as a team. You can exchange experience, opinions, and it’s easier to look at a problem from multiple angles when multiple developers are involved.

First, make sure that everybody in the team is aware of the problem. Defining it altogether is the best. If you have a doubt that somebody is not on the same page, you can re-explain it using different words. It might bring more insights and ideas to the discussion.

Don’t assume that everybody understands the problem equally. Words are powerful, but they are also ambiguous; never hesitate to ask questions (even if they seem stupid at first), and encourage the team to do the same. If your colleagues see that you’re not afraid to ask, it will give them confidence to do the same.

The ambiguity can also build overtime, after the problem was discussed. That’s why it’s really important to document the whole process, for anybody to be able to look at it again and fix the possible creeping misconceptions. Don’t try to describe everything, but try to be specific enough. It’s a delicate balance, and you’ll get better at it with experience.

If you don’t like writing, I’d recommend you to try anyway: this is a powerful skill which will be useful in many areas of your life.

Regarding the team of problem solvers, diversity is important. Diversity of opinion, experience, background, you name it. The more diverse the opinions and ideas are, the more chances you’ll have to solve the problem satisfyingly (more on that later). If the members of the team have enough respect, humility, and know how to listen to their colleagues , you’re in the perfect environment to solve problems.

As developers, we’re dealing with moving systems, because they need to reflect the ever-changing business domain of the company you’re working with. These problems are unique, and even if similar problems might have been solved in the past, they’re never the exactly same. The differences can have an impact on the solution, sometimes insignificant (allowing you to re-apply the solution found previously), sometimes important enough to change the solution entirely.

Exploring the Solution Space

Now that we’ve defined the problem, thought about it with our team, tried to look at it from different angles, it’s time to try to find solutions, or at least to make a decision.

What is a good decision? The one which will bring you closer to your desired outcome. It sounds obvious, but there can be some ego involved in discussions, which will push us to try to be right even if it’s not the best solution in the current context. Our personal incentives can conflict with the company’s best interest; it’s always good to try to stay aware of that.

The solution should also be the simplest possible, while still moving forward to the desired outcome. It should also have an acceptable level of risk when we decide to apply the solution. In my experience, complicated solutions are the ones which come up first: don’t stop there. Take some time trying to find the best solution with your team.

For example, here’s what we do with my actual team:

  • We define the problem altogether.
  • We try to think about different hypothesizes. Not only one, but a couple of them.
  • We write the benefits and drawbacks of each hypothesis (which can lead to more ideas, and possibly more hypothesizes).
  • We commit to a hypothesis, which then needs to be implemented.

What I meant by “hypothesis” here is a solution which might work; but only the implementation of the hypothesis can be considered as a solution. Before the implementation, it’s just an informed guess. Many things can go wrong during an implementation.

This process looks simple, but when you have multiple developers involved, it’s not. Again, if each member of the team have good soft skills and some experience, it can be an enjoyable and rewarding process. But you need a good team for it to work efficiently (that’s why it’s so important to ask the good questions when joining a company). It’s even better if the members of the team are used to swim in uncertainty, and take it as a challenge more than a chore.

The process described above is just an example; in practice it’s often more chaotic. For example, even when a decision is made, your brain might still continue to process the problem passively. If you find some flaws in the hypothesis you’ve committed to, congratulations! You have now a brand-new problem.

I can’t emphasize it enough: try to be as detached as possible from your ideas, opinions, and preferred hypothesizes. The goal is not for you to be right and feel good, but for your company to move in the good direction. It’s hard, but with practice it gets easier.

I also want to underline the importance of finding both benefits and drawbacks for the different hypothesizes you (and your team) came up with.

To find good solutions, we might also need to reduce the uncertainty around their possible consequences. Doing some external research can help, like gathering data around the problem and the possible hypothesizes. In the best case scenario, if you can find enough data, and if you feel confident that you can move forward with a hypothesis, that’s already a great victory.

If you don’t have enough external information to reduce the uncertainty to a level you feel comfortable with, look at your past experience. Try to find problems similar to the one your deal with in the present, and try to think about the solutions applied at the time, to see if they could also be applied in your current case. But be careful with this approach: complex problems are context-sensitive, and the context you were in the past will never be exactly the same as the present and future contexts.

For example, I recently changed the way we display search results in our system, because we had some data indicating that some users had difficulties to find what they really wanted to find. The problem: users have difficulties to find the good information; it’s a recurrent problem which might never be 100% solved. That said, thanks to the data gathered, we found an easy way to improve the situation.

The data was very clear and specific, but it’s not always the case. More often than not, your data won’t really prove anything. It might only show correlations without clear causality. It will be even more true if you begin by gathering data without defining first the problem you try to solve. You can find problems looking at some data, that’s true, but it needs care and deep understanding of what you’re doing; looking at data when you know exactly what you want to solve works better.

Using this kind of process, the hypothesis is often some sort of compromise. That’s fine; committing to a hypothesis is not the end of the process, and there will be other occasions to revisit and refine the solution.

If you don’t feel comfortable with the level of uncertainty of the problem (or the risk involved by applying your hypothesis), you need to dig more. Writing a prototype can be useful for example, if you hesitate between two or more approaches. If your prototype is convincing enough, it can also be useful to gather feedback from your users, even if the ones testing your hypothesis will always be more invested if they test a real-life functionality, instead of a prototype which might use dummy data, or be in a context which is too remote from the “real” context.

In my opinion, prototypes are not always useful for complex problems, because a prototype only test a new feature at time T, but doesn’t allow you to see if the solution stay flexible enough overtime. That’s often a big concern: how will the solution evolve?

But prototyping can still help gather information and reduce the uncertainty of the problem, even if the prototype doesn’t really give you the solution on a silver platter. It’s also great for A/B testing, when you’re in the (likely) case when you have not much information about the real needs of your users. You could ask them of course, but nothing guarantee that they know themselves what these needs are.

If you don’t find any satisfying hypothesis to your problem, you might also challenge the desired outcome. Maybe a similar, simplest hypothesis, with slightly different outcomes, could work better? If it makes things easier, faster, and less complex, it could be the best solution. Don’t hesitate to challenge your stakeholders directly on the desired outcomes.

Deferring the Problem

In some cases, you might be hesitant to try to solve a problem if there is still too much uncertainty around it. In that case, it might be best to defer solving the problem altogether.

Deferring the problem means that you don’t solve it now ; you keep things as they are, until you get more information to reduce the uncertainty enough.

We had a problem in the company I worked with some time ago: we have dosages which can be discovered in articles, but users didn’t really find them, and nobody really knew why. Because of this lack of information, the problem was not tackled right away, but differed. From there, data have been collected overtime, allowing us to understand the scope of the problem better.

Don’t forget that deferring a problem is already taking a decision. It might be the less disruptive decision for the application and its codebase, but it’s s decision nonetheless, and it can have consequences. Seeing a differed problem as a decision will push you to think about the possible consequences of your inaction, and you’ll look at it as a partial “solution”, with some uncertainty and risk associated to it.

In my experience, deferring the problem works well only when you try to actively seek more data to solve it later. It can be some monitoring to see how the problem evolves, or some data taken from users’ actions. Sometimes, simply waiting can also give you important information about the nature of the problem.

What you shouldn’t do is try to forget the problem. It might come back in force to haunt your sleepless nightmares later. Avoiding a problem is not deferring it.

Here’s another example: we began recently to build some CMS tooling for medical editors, for them to write and edit content on our learning platform. We had one GraphQL API endpoint at the beginning, providing data to two different part of the application:

  • Our CMS for medical editors.
  • Our learning platform for medical students.

We knew that using one single GraphQL endpoint for these two types of users could cause some problems.

But we didn’t do anything about it, mostly because we didn’t see any real, concrete problem, at least at first. When a minor symptom, related to this unique endpoint, popped up, we spoke about it, and we still chose not to do anything. We preferred deferring the problem once more, to try to solve the real problem (one API for two different kinds of applications) later.

Finally, when we had enough symptoms and some frustration, we decided to split our graphQL API in two different endpoints. It was the best moment to do so: we had enough information to come up with a good decision, we applied it, and we stayed vigilant, to see how our applied hypothesis would evolve.

Moving fast and breaking things is not always the best solution. In some situations, waiting a bit and see how things evolve can allow you to solve your problems in a more effective way. But, as always, it depends on the problem, its context, and so on.

Reading this article, you might have wondered: how much information is enough to be comfortable enough to apply a solution? Well, again, your experience will be the best judge here. You’ll also need to consider carefully risks, benefits, and drawbacks. It doesn’t mean that you need to chicken out if you don’t have 100% certainty about a problem and some hypothesizes; being a software developer implies to have some courage and accept that mistakes will be made. It’s not an easy task, and there is no general process to follow in any possible case.

In short: use your brain. Even if you’re totally wrong, you’ll have the opportunity to fix the bad decisions you’ve made before the implementation, during the implementation, and even after it. We don’t code in stone.

The Implementation: The Value of Iteration

You’ve gathered with your team, tried to define the problem, found multiple hypothesizes, and agreed to try one of them. Great! Problem solved.

Not so fast! We still need to apply the hypothesis, and hope that it will become a good solution to the problem. Doing so, you’ll gather more information along the way, which might change your perspective on the problem, on your hypothesizes, and can even create some baby problems on its own.

It’s where the agile methodology is useful: since we’ll never have 100% certainty regarding a problem and its possible solution, we’ll learn more about both while implementing the hypothesis. That’s why it’s so valuable to iterate on the implementation: it gives you more information to possibly adjust your code, or even the problem, or even switching hypothesizes altogether. Who knows? A solution which is not implemented is just a guess.

If the hypothesis applied is not the ones you would have personally preferred (compromising, or even giving up on your preferred solution is common in a team), only applying it will tell you if you’re right or wrong; that is, if the hypothesis can become a solution solving the problem, at least in the present context.

If you’re worried about how a specific solution will evolve overtime, it’s more complicated, because an implementation won’t give you the information you seek. Still, implementing a hypothesis can be a great source of learning (the most valuable to me is when I’m wrong, because I learn even more). If you think that your hypothesis can have better outcome at time T, you might also try to implement it and compare it. Again, it’s where prototyping is useful.

When applying the solution, you need to look at the details of the implementation, as well as the big picture, to judge if the solution you’re creating is appropriate (leading to the desired outcome). This is a difficult exercise. In general, a developer should be able to reason on different levels of abstraction, more or less at the same time. Again, if you’re aware of it, your experience will help you here, and you can also push yourself to think of all the possible risks and consequences at different levels.

If you work in a team, try to participate (at least a bit) into the implementation of the solution. It’s not good to create silos in teams (that is, only a couple of members have some information others don’t have).

You can go as far as looking at other projects, and ask yourselves these questions:

  • Did we had similar problems on these other projects? How did we solve them?
  • What was the context of these projects? Is it similar to our current context?
  • What did we learn from these other problems, and their implementation? Is the implementation similar to what we’re doing now?

In any case, I would definitely recommend you to write a development journal. I write mine for years, and it has been valuable in many cases. I basically write in there:

  • The interesting problems I had.
  • The decisions made.
  • How the implementation of the solution evolved overtime.
  • The possible mistakes we made along the way.

It’s a great resource when you have a problem and you want to look at your past experience.

To evaluate your decisions overtime, nothing will beat a good monitoring process: logs, tests, and so on. It’s what the book Building Evolutionary Architecture call “fitness functions” for example, some monitoring allowing you to measure how healthy your architecture stays overtime. It doesn’t have to stop to the architecture; you can think about different monitoring system to see how something evolve, especially if the solution has still a lot of uncertainty regarding its benefits, drawbacks, and risks.

You can also do that retrospectively: looking at how the code complexity evolve overtime using Git for example.

Retrospective on the Process

We defined the problem, implemented a solution iteratively, and now the problem is gone. That’s it! We made it! Are we done now?

Decisions are sometimes not optimal, and implementing a solution successfully doesn’t mean that there wasn’t a better (simpler) one to begin with. That’s why it can be beneficial to look back and understand what went right, and what went wrong. For example, we can ask ourselves these questions:

  • Looking at what we learned during the whole process, is there a potentially better hypothesis to solve the problem in a simpler, more robust way?
  • What are the benefits and drawbacks we missed when speaking about the different hypothesizes, but we discovered during the implementation? Why we didn’t think about them beforehand?
  • What other problems did we encounter during the implementation? Did we solve them? Did we differ some? What should be the next steps regarding these new problems?
  • What kind of monitoring did we put in place to make sure that the solution won’t have undesired outcomes overtime? Can we learn something with this data?

Reflecting on past solutions is a difficult thing to do. There is no way to logically assess that the decision taken was better than others, since we didn’t implement the other hypothesizes, and we didn’t look at them overtime to appreciate their consequences. But you can still look at the implementation of the solution overtime, and write in your developer journal each time there is a bug which seems directly related to the solution. Would the bugs be the same if another solution would had been applied?

Bugs are often not an option; they will pop up, eventually. Nonetheless, it’s important to make sure that you can fix them in a reasonable amount of time, and that you don’t see them creeping back in the codebase after being solved. Some metrics, from the DevOps movement (like MTTR for example) can help here. Sometimes, bugs will show you a better, more refined solution to the original problem; after all, bugs can also give you some useful information. They are also the most direct result of the implementation of your solution.

If you want to know more about measuring complexity (which can be also used to measure complexity overtime after applying a solution), I wrote a couple of articles on the subject .

Humility in Problem-Solving

It’s time to do a little summary. What did we see in this article?

  • We need to ensure that the problem we found is really a problem we need to solve. Is there any value to solve the problem? Is it even a problem?
  • Try to determine what kind of problem you have: a problem which can have multiple, specific, known answers (like a technical problem), or a problem which depends on the real-life context, without known solutions?
  • Defining the problem is important. Try to define it using different words. Write these definitions down. Does everybody in your team understand the problem equally?
  • It’s time to explore the solution space. Draft a couple of hypothesizes, their benefits, drawbacks, and risks. You can also do some prototyping if you think it would give you more information to take the best decision.
  • Do you have enough information to implement a hypothesis, becoming effectively a solution? If it’s not the case, it might be better to keep the status quo and try to solve the problem later, when you’ll have more information. But don’t forget the problem!
  • If you decide to implement a solution, do it step by step, especially if you’re unsure about the consequences of your decisions. Implement an independent part of the hypothesis, look at the consequences, adjust if necessary, and re-iterate.
  • When the solution is implemented, it’s time to reflect on the whole process: did we solve the problem? What other problems did we encounter? Maybe another solution would have been better? Why?

As I was writing above, most problems you’ll encounter will be complex ones, embedded into a changing environment with different moving parts. As a result, it’s difficult to train to solve problems in a vacuum; the only good training I know is solving real life problems. That’s why your experience is so important.

Experience build your intuition, which in turn increase your expertise.

You’ll never have 100% certainty that a solution will bring you the desired outcome, especially if you are in front of a complex problem with a blurry context. If you are absolutely convinced that you have the good solution without even beginning to implement it, I’d advise you to stay humber in front of the Gods of Complexity, or they will show you how little you know.

  • How to solve it
  • Hammock Driven Development
  • When Deferring Decisions Leads to Better Codebases
  • Lean Development - deferring decision

how do programmers approach problem solving and coding

  • Latest Articles
  • Top Articles
  • Posting/Update Guidelines
  • Article Help Forum

how do programmers approach problem solving and coding

  • View Unanswered Questions
  • View All Questions
  • View C# questions
  • View C++ questions
  • View Javascript questions
  • View Visual Basic questions
  • View Python questions
  • CodeProject.AI Server
  • All Message Boards...
  • Running a Business
  • Sales / Marketing
  • Collaboration / Beta Testing
  • Work Issues
  • Design and Architecture
  • Artificial Intelligence
  • Internet of Things
  • ATL / WTL / STL
  • Managed C++/CLI
  • Objective-C and Swift
  • System Admin
  • Hosting and Servers
  • Linux Programming
  • .NET (Core and Framework)
  • Visual Basic
  • Web Development
  • Site Bugs / Suggestions
  • Spam and Abuse Watch
  • Competitions
  • The Insider Newsletter
  • The Daily Build Newsletter
  • Newsletter archive
  • CodeProject Stuff
  • Most Valuable Professionals
  • The Lounge  
  • The CodeProject Blog
  • Where I Am: Member Photos
  • The Insider News
  • The Weird & The Wonderful
  • What is 'CodeProject'?
  • General FAQ
  • Ask a Question
  • Bugs and Suggestions

how do programmers approach problem solving and coding

The Beginner Programmer's guide to Problem Solving [With Example]

how do programmers approach problem solving and coding

Have you got this feeling that you are able to grasp the concepts of programming and  you are able to understand what’s a variable, what’s a function, what are data types, etc. yet you find it difficult to solve problems in programming.  Every beginner gets this feeling.  I did too when starting out.

It is important to overcome this feeling at the earliest, otherwise it can form a mental block for you.

Image 1

How it can be a mental block to you?  Common sense says that the more you practice a certain skill, you get better at that skill as time progresses.  Same goes with problem solving too.  The more problems you solve, the better you become at problem solving.  But when you get a feel that you are trying hard and still unable to solve a problem or find it extremely difficult, your confidence lowers.  At this stage, either you stop solving problems or try to solve lesser number of problems.

The point is your curriculum or your professional work is generally designed in such a manner that the order of difficulty increases as time progresses.  So, you are in a situation where you feel less confident in solving small problems but now tasked with solving bigger problems.  And the cycle continues till it becomes a permanent mental block in you.

Is it too late to start solving problems?

No.  If you have come to the realization that you need to improve your problem solving skills, you have made that good first step.  Quite often our egos don’t let us accept the obvious.  It is good to accept certain truth because that is the only way that we can improve ourselves.

What can I do to become better at solving problems?

Remove the mental block first – exercise your mind.

Your mind is your most powerful weapon.  So you have to think you can actually solve the problem.  So from today, think positively that you can solve any problem.  But you will obviously start with small problems and go on to solve bigger problems.

As with every aspect in life, it starts with conditioning the mind.  So, starting today, tell yourselves the following:

  • I can solve any problem that is put at me
  • I will commit at least 1-2 hours per day on solving problems alone for the next 30 days
  • I will never give up on any problem that is put at me, I will ask for help if required.1

Understand the basic approach to problem solving

Do you know one of the reasons for your struggle with problem solving?  One reason might be due to lack of practice.  But the main reason is because you have not understood the basics of problem solving especially in programming.  Once you understand the approach to problem solving to the smallest of things, you can go ahead and solve bigger and more complex problems with confidence.1

Ever wondered how top tech companies like Google, Amazon solved the internet’s biggest & hardest problems?  The answer is simplicity.  They solved problems at the basic level and then went on to solve bigger and bigger problems.  You can do it too.  But you need to be good at the basics.

What do I need to understand before even trying to solve the problem?

Understand the problem clearly – the power of clarity.

You need to understand your problem clearly before even trying to solve it1.  Lack of clarity at this stage will put you down.  So make a conscious effort in understanding the problem more clearly.  Ask questions like What, Why, When, Where, What if and How.  Not all questions might be applicable to your problem, but it is important to ask questions to yourself at this stage before you go ahead trying to solve the problem.

Visualize – The Power of visualization

I am sure everyone of you is aware of what visualization is.  Trying to picturize your thoughts.  Have you ever imagined how some people can solve extra ordinary problems just by looking into those problems and they will instantly have a solution to it?  And we don’t even understand the problem fully?  It is because they do it with their mind.  They visualize the problem in their minds and they solve it in their minds itself.  Visualization is a powerful tool in your mind.

But in order to get to that state, first you need to visualize the problem externally.  That is where a pen and a paper/notebook (or) a white board comes into play1.  Try to visualize the problem at hand and try to picturize the problem.  That is also one of the steps to make sure that you understand the problem clearly.

There was a situation when I and my dear friend & colleague were discussing about a problem and we were literally going nowhere.  This was actually when we each had around 7 years of experience in the industry.  At that point, my friend said “Let’s put our points in board.  If we don’t put it on the board, we will never get started”.  And we started putting things on board.  Things started to get more clear and raised more questions and ultimately became more clear.

That is the power of visualization.  It really helps us to get started with our thinking. This visual thing works.  Just try it out.

Your next question might be “I kinda get it, but I don’t.  How do I visualize? What exactly do I visualize?”.  Please read on to find out the answers.

What is the basic approach to problem solving

Step 1:  identify small problems.

The major trick in problem solving is to identify and solve the smallest problem and then moving ahead with bigger ones.  So how do you do it?

The answer is division of responsibility.  Simply put, we need to identify parts that can stand on its own and identify a sequence in those responsibilities.  And once you start breaking down the problems into smaller ones, then you can go ahead with the next step.

Step 2:  Solve the smaller problems one at a time

Now that you have identified the smaller problems, try to solve them.  While solving them, make sure that you are focussing only on one problem at a time.  That makes life much simpler for us.  If you feel that this smaller problem is too big to solve on its own, try to break it down further.  You need to iterate steps 1 to step 3 for each smaller problem.  But for now, ignore the bigger problem and solve the rest of the problems.

  • It is ok to assume that other problems are solved
  • It is ok to hardcode when coding a particular problem, but later you will resolve it in step 3.
  • Solve the easier problems first, that will give you confidence and momentum until you get the confidence to solve the hardest problem first.

Step 3: Connect the dots (Integration)

You have solved individual problems.  Now it is time to connect the dots by connecting the individual solution.  Identify those steps which will make the solution or the program complete.  Typically in programming, the dots are connected by passing data that is stored in variables.

Step 4: Try to optimize each step & across steps

Once you are completed with a working solution, try to optimize the solution with the best code that you can write.  This comes only with practice.  This trick can make a difference between a good programmer and a great programmer.  But to get to this step, you need to be first good at steps 1 to 3.

Let’s take an example & walkthrough the problem solving approach

Problem:  check if a user given string is a palindrome or not.

I will be using Python for this exercise (Although I have experience in1 C# and JAVA, I am also a Python beginner, so pardon any bad code).  Let’s iterate through our steps:

Let’s call this as Level 1:

Step 1:  Identify smaller problems:

Image 2

Step 2: Solve the small problems

So each small problem will map to its corresponding solution as below:

Image 3

Note: When solving the step (3.  Compare the variables), I am doing 2 things:

  • I am making an assumption that reversed is the variable name of the reversed string.
  • I am hardcoding the variable name reversed to ‘madam’ to avoid compile time error
  • If you execute the program at this state, you can input ‘madam’ and check if it is printing ‘The given string is a palindrome’ (And) you can input something else like ‘dog’ and check if it is printing ‘The given string is not a palindrome’

When we are trying to connect the dots, the only thing that is missing now is the variable reversed is hardcoded.  For that to be set to the correct value, we need to break the small problem (Reverse the user input and store in a separate variable) into further smaller problems.  Till that point we need to mark it as incomplete.

2 things still remain unsolved in Level 1:

  • Solution for step 2 in the diagram (Reverse the user input and store in a separate variable)
  • Connecting the dots once the solution for step 2 is found

Iterating small problem 2 through our problem solving steps:

Let’s call this Level 2:

Step 1: Identify smaller problems

Image 4

Step 3: Connect the dots

Here, we have already connected the dots.  So we need not do anything extra in this step.

Now we have solved the smaller problems, which means Level 2 is over.  Now we need to come back to Level 1.

If you remember, 2 things remain in Level 1.  One is solution for step 2 which we have found now.  Two is connecting the dots.

Now if we substitute the small problem 2 with the solution that we derived just now, we get something like this:

Image 6

The thing that remains is connecting the dots.

So if we see what is the missing connection, the variable reversed is set twice.  One to the solution of step 2 and another is hardcoded in step 3.  So we can now remove the hardcoded value in step 3, in which case our code will become like this

Image 7

If you see, we have actually solved our problem.

We are left with step 4 – Optimize each step and across steps

Step 4: Try to optimize each step and across steps

As you can see, there are many things that needs to be optimized for this code.  I would leave you to optimize the code further.  Come on, put on your thinking cap and try different solutions.

BONUS STEP 5:  Make the code robust

By robust I mean,

  • Adding error & exception handling
  • Using better variable names
  • Adding user defined functions
  • Adding comments where necessary

Again, I would leave you to figure out how to do this step.

  • We saw just how we can solve problems using a step by step approach
  • By solving smaller problems, I get into a momentum for solving bigger & tougher problems
  • By focussing one problem at a time, I am eliminating distractions, thus allowing to better direct your efforts for that one problem rather than getting confused with many small problems at hand.
  • If you understand this approach and practice, you will definitely go on to solve bigger problems and your confidence will raise.
  • Beauty about breaking down the problem is that we can further convert each problem and sub problem into separate functions/modules thus making the code more modularized and maintainable.

Wait, You can’t leave yet:

Now dear beginner programmers, take any problem and try to apply this approach.  See the results for yourselves.  Now, describe the following in the comments section:

  • What problem you are solving?
  • How did you break it down? (Even a snap of your notebook page or board will do!)
  • The final code
  • How did you feel and what did you learn from this exercise?

Also remember, I am challenging you for the 30 day problem solving challenge.

If you liked this blog post, please feel free to share it with your circles in social media.

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Twitter

Comments and Discussions

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

how do programmers approach problem solving and coding

Onecodecamp

Mastering Programming Challenges: Five In-Depth Problem-Solving Strategies

how do programmers approach problem solving and coding

  • Posted on 22/08/2023
  • chuapristine16
  • No Comments

Practicing problem-solving techniques is crucial for becoming a proficient programmer . Whether you’re a beginner or an experienced coder, honing your problem-solving skills can greatly improve your ability to tackle programming challenges effectively.

Here are some strategies and techniques to help you in this endeavor:

  • Understand the Problem: Before you start coding , it’s essential to thoroughly understand the problem statement. Break it down into smaller components and ensure you grasp the requirements, constraints, and the expected input-output relationship. Consider asking questions like: What are the input types and their ranges? What should the output look like? Are there any edge cases to consider? A solid understanding of the problem will guide your solution and prevent misunderstandings that might lead to incorrect implementations.
  • Break Down the Problem: Large problems can often be intimidating, but breaking them down into smaller subproblems can make them more manageable. Identify the main steps or components needed to solve the problem. Tackle each subproblem one at a time, focusing on solving each part independently. Once you have working solutions for the subproblems, combine them to solve the larger problem. This approach not only simplifies complex problems but also allows you to approach each part with a clear strategy.
  • Algorithm Design: Choosing the right algorithmic approach is critical for efficient problem-solving. Different types of problems often have established algorithms that work well for them. For instance, if you’re dealing with a search problem, consider binary search for efficiency. If the problem involves finding the shortest path, graph algorithms like Dijkstra’s or A* might be useful. Understanding the problem’s characteristics and selecting an appropriate algorithmic paradigm will significantly influence the efficiency and correctness of your solution.
  • Pseudocode and Visualization: Before diving into coding, sketch out a high-level pseudocode that outlines the steps your solution will take. Pseudocode helps you structure your thoughts and visualize the solution’s logic without getting bogged down in syntax. It serves as a roadmap for implementing the actual code. Visualizing the algorithm’s flow through pseudocode allows you to spot potential issues and refine your approach before committing to coding.
  • Test Cases: Creating a well-defined set of test cases is crucial for ensuring the correctness of your solution. Start with common cases, and then expand to cover edge cases and corner cases. These might include situations where the input is at its maximum or minimum values, or scenarios that involve unusual combinations of inputs. By testing your solution against these cases, you can catch errors and ensure your solution handles all possible scenarios accurately.

Remember that problem-solving is a skill that takes time to develop. It’s okay to face challenges and make mistakes; they are valuable learning experiences. With consistent practice and dedication, you’ll see significant improvement in your ability to tackle programming challenges effectively.

Leave a Comment Cancel reply

Reserve my spot.

Please Login First to Download the Carriculum!

Download Curriculum

Download syllabus.

how do programmers approach problem solving and coding

UNIT 1: How to Think Like an Engineer.

Learning objectives.

  • Explain what we mean by “Computational Thinking”.
  • Describe the problem being solved in a computational algorithm.
  • Explain the process for generating computational algorithms.
  • Generate and test algorithms to solve computational problems.
  • Evaluate computational algorithms for exactness, correctness, termination, generalizability and understandability.
  • Explain the role of programming in the field of Informatics.

Introduction

The goal of this book is to teach you to solve computational problems and to think like an engineer. Computational problems are problems that can be solved by the use of computations (a computation is what you do when you calculate something). Engineers are people who solve problems – they invent, design, analyze, build and test “things” to fulfill objectives and requirements. The single most important skill for you to learn is problem solving. Problem solving means the ability to formulate problems, think creatively about solutions, and express a solution clearly and accurately. As it turns out, the process of learning to program is an excellent opportunity to practice problem-solving skills.

This book strives to prepare you to write well-designed computer programs that solve interesting problems involving data.

Computational Thinking

image

Figure 1: “The seven components to computational thinking”(www.ignitemyfutureinschool.org/about)

Computational Thinking is the thought processes involved in understanding a problem and expressing its solution in a way that a computer can effectively carry out. Computational thinking involves solving problems, designing systems, and understanding human behavior (e.g. what the user needs or wants) – thinking like an engineer. Computational thinking is a fundamental skill for everyone, not just for programmers because computational thinking is what comes before any computing technology. [1]

Computer science is the study of computation — what can be computed and how to compute it whereas computational thinking is:

Conceptualizing , not programming. Computer science is not only computer programming. Thinking like a computer scientist means more than being able to program a computer. It requires thinking at multiple levels of abstraction;

Fundamental , not rote skill. A fundamental skill is something every human being must know to function in modern society. Rote means a mechanical routine;

A way that humans, not computers, think . Computational thinking is a way humans solve problems; it is not trying to get humans to think like computers. Computers are dull and boring; humans are clever and imaginative. We humans make computers exciting. Equipped with computing devices, we use our cleverness to tackle problems we would not dare take on before the age of computing and build systems with functionality limited only by our imaginations;

Complements and combines mathematical and engineering thinking . Computer science inherently draws on mathematical thinking, given that, like all sciences, its formal foundations rest on mathematics. Computer science inherently draws on engineering thinking, given that we build systems that interact with the real world;

Ideas , not artifacts. It’s not just the software and hardware artifacts we produce that will be physically present everywhere and touch our lives all the time, it will be the computational concepts we use to approach and solve problems, manage our daily lives, and communicate and interact with other people;

For everyone, everywhere . Computational thinking will be a reality when it is so integral to human endeavors it disappears as an explicit philosophy. [2]

how do programmers approach problem solving and coding

Figure 2 “Are you happy?” by Typcut http://www.typcut.com/headup/are-you-happy

An algorithm specifies a series of steps that perform a particular computation or task. Throughout this book we’ll examine a number of different algorithms to solve a variety of computational problems.

Algorithms resemble recipes. Recipes tell you how to accomplish a task by performing a number of steps. For example, to bake a cake the steps are: preheat the oven; mix flour, sugar, and eggs thoroughly; pour into a baking pan; set the timer and bake until done.

However, “algorithm” is a technical term with a more specific meaning than “recipe”, and calling something an algorithm means that the following properties are all true:

  • An algorithm is an unambiguous description that makes clear what has to be implemented in order to solve the problem. In a recipe, a step such as “Bake until done” is ambiguous because it doesn’t explain what “done” means. A more explicit description such as “Bake until the cheese begins to bubble” is better. In a computational algorithm, a step such as “Choose a large number” is vague: what is large? 1 million, 1 billion, or 100? Does the number have to be different each time, or can the same number be used again?
  • An algorithm expects a defined set of inputs. For example, it might require two numbers where both numbers are greater than zero. Or it might require a word, or a list customer names.
  • An algorithm produces a defined set of outputs. It might output the larger of the two numbers, an all-uppercase version of a word, or a sorted version of the list of names.
  • An algorithm is guaranteed to terminate and produce a result, always stopping after a finite time. If an algorithm could potentially run forever, it wouldn’t be very useful because you might never get an answer.
  • Must be general for any input it is given. Algorithms solve general problems (determine if a password is valid); they are of little use if they only solve a specific problem (determine if ‘comp15’ is a valid password)
  • It is at the right level of detail…..the person or device executing the instruction know how to accomplish the instruction without any extra information.

Once we know it’s possible to solve a problem with an algorithm, a natural question is whether the algorithm is the best possible one. Can the problem be solved more quickly or efficiently?

The first thing you need to do before designing an algorithm is to understand completely the problem given. Read the problem’s description carefully, then read it again. Try sketching out by hand some examples of how the problem can be solved. Finally consider any special cases and design your algorithm to address them.

An algorithm does not solve a problem rather it gives you a series of steps that, if executed correctly, will result in a solution to a problem.

An Example Algorithm

Let us look at a very simple algorithm called find_max.

Problem : Given a list of positive numbers, return the largest number on the list.

Inputs : A list of positive numbers. This list must contain at least one number. (Asking for the largest number in a list of no numbers is not a meaningful question.)

Outputs : A number, which will be the largest number in the list.

Algorithm :

  • Accept a list of positive numbers; set to nums_list
  • Set max_number to 0.
  • If the number is larger, set max_number to the larger number.
  • max_number is now set to the largest number in the list of positive numbers, nums_list.

Does this meet the criteria for being an algorithm?

  • Is it unambiguous? Yes. Each step of the algorithm consists of uncomplicated operations, and translating each step into programming code is straight forward.
  • Does it have defined inputs and outputs? Yes.
  • Is it guaranteed to terminate? Yes. The list nums_list is of finite length, so after looking at every element of the list the algorithm will stop.
  • Is it general for any input? Yes. A list of any set of positive numbers works.
  • Does it produce the correct result? Yes. When tested, the results are what are expected

[3] Figure 3: Example Algotithm

Verifying your Algorithm

How do we know if an algorithm is unambiguous, correct, comes to an end, is general AND is at the right level of detail? We must test the algorithm. Testing means verifying that the algorithm does what we expect it to do. In our ‘bake a cake’ example we know our algorithm is ‘working’ if, in the end, we get something that looks, smells and tastes like a cake.

how do programmers approach problem solving and coding

Figure 4 “ Keyboard ” by Geralt is licensed under CC 2

Your first step should be to carefully read through EACH step of the algorithm to check for ambiguity and if there is any information missing. To ensure that the algorithm is correct, terminates and is general for any input we devise ‘test cases’ for the algorithm.

A test case is a set of inputs, conditions, and expected results developed for a particular computational problem to be solved. A test case is really just a question that you ask of the algorithm (e.g. if my list is the three numbers 2, 14, and 11 does the algorithm return the number 14?). The point of executing the test is to make sure the algorithm is correct, that it terminates and is general for any input.

Good (effective) test cases:

  • are easy to understand and execute
  • are created with the user in mind (what input mistakes will be made? what are the preconditions?)
  • make no assumptions (you already know what it is supposed to do)
  • consider the boundaries for a specified range of values.

Let us look at the example algorithm from the previous section. The input for the algorithm is ‘a list of positive numbers’. To make it easy to understand and execute keep the test lists short. The preconditions are that the list only contains numbers and these numbers must be positive so include a test with a ‘non-number’ (i.e. a special character or a letter) and a test with a negative number. The boundaries for the list are zero and the highest positive number so include a test with zero and a large positive number. That is it! Here is an example of three different test cases.

Manually, you should step through your algorithm using each of the three test cases, making sure that the algorithm does indeed terminate and that you get your expected result. As our algorithms and programs become more complex, skilled programmers often break each test case into individual steps of the algorithm/program and indicate what the expected result of each step should be. When you write a detailed test case, you don’t necessarily need to specify the expected result for each test step if the result is obvious.

In computer programming we accept a problem to solve and develop an algorithm that can serve as a general solution. Once we have such a solution, we can use our computer to automate the execution. Programming is a skill that allows a competent programmer to take an algorithm and represent it in a notation (a program) that can be followed by a computer. These programs are written in programming languages (such as Python). Writing a correct and valid algorithm to solve a computational problem is key to writing good code. Learn to Think First and coding will come naturally!

Computational problem solving does not simply involve the act of computer programming. It is a process, with programming being only one of the steps. Before a program is written, a design for the program must be developed (the algorithm). And before a design can be developed, the problem to be solved must be well understood. Once written, the program must be thoroughly tested. These steps are outlined in Figure 5.

how do programmers approach problem solving and coding

Figure 5: Process of Computational Problem Solving

Values and Variables

A value is one of the basic things computer programs works with, like a password or a number of errors.

Values belong to different types: 21 is an integer (like the number of errors), and ‘comp15’ is a string of characters (like the password). Python lets you give names to values giving us the ability to generalize our algorithms.

One of the most powerful features of a programming language is the ability to use variables. A variable is simply a name that refers to a value as shown below,

Whenever the variable errors appears in a calculation the current value of the variable is used.

We need some way of storing information (i.e. the number of errors or the password) and manipulate them as well. This is where variables come into the picture. Variables are exactly what the name implies – their value can vary, i.e., you can store anything using a variable. Variables are just parts of your computer’s memory where you store some information. Unlike literal constants, you need some method of accessing these variables and hence you give them names.

Programmers generally choose names for their variables that are meaningful and document what the variable is used for. It is a good idea to begin variable names with a lowercase letter . The underscore character (_) can appear in a name and is often used in names with multiple words.

What is a program?

image

Figure 6: “ Python Code ” by nyuhuhuu is licensed under CC-BY 2.0

A program is a sequence of instructions that specifies how to perform a computation. The computation might be something mathematical, such as solving a system of mathematical equations or finding the roots of a polynomial, but it can also be a symbolic computation, such as searching and replacing text in a document or something graphical, like processing user input on an ATM device.

The details look different in different computer programming languages, but there are some low-level conceptual patterns (constructs) that we use to write all programs. These constructs are not just for Python programs, they are a part of every programming language.

input Get data from the “outside world”. This might be reading data from a file, or even some kind of sensor like a microphone or GPS. In our initial algorithms and programs, our input will come from the user typing data on the keyboard.

output Display the results of the program on a screen or store them in a file or perhaps write them to a device like a speaker to play music or speak text.

sequential execution Perform statements one after another in the order they are encountered in the script.

conditional execution Checks for certain conditions and then executes or skips a sequence of statements.

repeated execution Perform some set of statements repeatedly, usually with some variation.

reuse Write a set of instructions once and give them a name and then reuse those instructions as needed throughout your program.

Believe it or not, that’s pretty much all there is to it. Every computer application you’ve ever used, no matter how complicated, is made up of constructs that look pretty much like these. So you can think of programming as the process of breaking a large, complex task into smaller and smaller subtasks until the subtasks are simple enough to be performed with one of these basic constructs. The “art” of writing a program is composing and weaving these basic elements together many times over to produce something that is useful to its users.

Computational Problem Design using the Basic Programming Constructs

The key to better algorithm design and thus to programming lies in limiting the control structure to only three constructs as shown below.

  • The Sequence structure (sequential execution)
  • The Decision, Selection or Control structure (conditional execution)
  • Repetition or Iteration Structure (repeated execution)

image

Figure 7: the 3 Programming Constructs

  Let us look at some examples for the sequential control and the selection control.

Sequential Control Example

The following algorithm is an example of sequential control .

Problem : Given two numbers, return the sum and the product of the two numbers.

Inputs : Two numbers.

Outputs : The sum and the product.

  • display “Input two numbers”
  • accept number1, accept number2
  • sum = number1 + number2
  • print “The sum is “, sum
  • product = number1 * number2
  • print “The product is “, product
  • Is it guaranteed to terminate? Yes. Sequential control, by its nature, always ends.
  • Is it general for any input? Yes. Any two numbers work in this design.
  • Does it produce the correct result? Yes. When tested, the results are what are expected.

Here is an example of three different test cases that are used to verify the algorithm.

Selection Control Examples

The following two algorithms are examples of selection control which uses the ‘IF’ statement in most programming languages.

Problem : Given two numbers, the user chooses to either multiply, add or subtract the two numbers. Return the value of the chosen calculation.

Inputs : Two numbers and calculation option.

Outputs : The value of the chosen calculation.

The relational (or comparison) operators used in selection control are:

= is equal to [in Python the operator is ==]

> is greater than

< is less than

>= is greater than or equal

<= is less than or equal

<> is not equal to [in Python the operator is !=]

  • display “choose one of the following”
  • display “m for multiply”
  • display “a for add”
  • display “s for subtract”
  • accept choice
  • display “input two numbers you want to use”
  • accept number1, number2
  • if choice = m then answer= number1 * number2
  • if choice = a then answer= number1 + number2
  • if choice = s then answer= number1 -number212. if choice is not m, a, or s then answer is NONE
  • display answer
  • Is it guaranteed to terminate? Yes. The input is of finite length, so after accepting the user’s choice and the two numbers the algorithm will stop.
  • Is it general for any input? Yes. Any two numbers work in this design and only a choice of a’m’, ‘a’, or ‘s’ will result in numeric output.

This example uses an extension of the simple selection control structure we just saw and is referred to as the ‘IF-ELSE’ structure.

Problem : Accept from the user a positive integer value representing a salary amount, return tax due based on the salary amount.

Inputs : One positive integer number.

Outputs : The calculated tax amount.

= is equal to  [in Python the operator is ==]

<> is not equal to  [in Python the operator is !=]

  • accept salary
  • If salary < 50000 then
  • Tax = 0 Else
  • If salary > 50000 AND salary < 100000 then
  • Tax = 50000 * 0.05 Else
  • Tax = 100000 * 0.30
  • display Tax
  • Is it guaranteed to terminate? Yes. The input is of finite length, so after accepting the user’s number, even if it is negative, the algorithm will stop.
  • Is it general for any input? Yes. Any number entered in this design will work.

Iterative Control Examples

The third programming control is the iterative or, also referred to as, the repetition structure. This control structure causes certain steps to be repeated in a sequence a specified number of times or until a condition is met. This is what is called a ‘loop’ in programming

In all programming languages there are generally two options: an indefinite loop (the Python ‘WHILE’ programming statement) and a definite loop (the Python ‘FOR’ programming statement). We can use these two constructs, WHILE and FOR, for iterations or loops in our algorithms.

Note for Reader: A definite loop is where we know exactly the number of times the loop’s body will be executed. Definite iteration is usually best coded as a Python for loop. An indefinite loop is where we do not know before entering the body of the loop the exact number of iterations the loop will perform. The loop just keeps going until some condition is met. A while statement is used in this case.

The following algorithm is an example of iterative control using WHILE .

Problem : Print each keyboard character the users types in until the user chooses the ‘q’ (for ‘quit’) character.

Inputs : A series of individual characters.

Outputs : Each character typed in by the user.

  • initialize (set) letter = ‘a’
  • WHILE letter <> ‘q’
  • ACCEPT letter
  • DISPLAY “The character you typed is”, letter
  • Is it guaranteed to terminate? Yes. The input is of finite length, so after accepting the user’s keyboard character, even if it is not a letter, the algorithm will stop.
  • Is it general for any input? Yes. Any keyboard character entered in this design will work.

The following algorithm is an example of iterative control using FOR . This statement is used when the number of iterations is known in advance.

Problem : Ask the user how many words they want to enter then print the words entered by the user.

Inputs : Number of words to be entered; this value must be a positive integer greater than zero. Individual words.

Outputs : Each word typed in by the user.

  • accept num_words (must be at least one)
  • repeat num_words times (FOR 1 to num_words)
  • accept word
  • DISPLAY “The word you entered is”, word
  • Is it guaranteed to terminate? Yes. The input is of finite length, so after accepting the user’s number of words to enter and any characters typed on the keyboard, even if it is not a ‘word’ per say, the algorithm will stop.
  • Is it general for any input? Yes. Any positive integer greater than zero and any size ‘word’ will work.

Here is an example of two different test cases that are used to verify the algorithm.

The Role of Programming in the Field of Informatics

image

Figure8: iPhone apps by Jaap Arriens/NurPhoto via Getty Images (abcnews.go.com)

You see computer programming in use every day. When you use Google or your smartphone, or watch a movie with special effects, there is programing at work. When you order a product over the Internet, there is code in the web site, in the cryptography used to keep your credit card number secure, and in the way that UPS routes their delivery vehicle to get your order to you as quickly as possible.

Programming is indeed important to an informatics professional as they are interested in finding solutions for a wide variety of computational problems involving data.

When you Google the words “pie recipe,” Google reports that it finds approximately 38 million pages, ranked in order of estimated relevance and usefulness. Facebook has approximately 1 billion active users who generate over 3 billion comments and “Likes” each day. GenBank, a national database of DNA sequences used by biologists and medical researchers studying genetic diseases, has over 100 million genetic sequences with over 100 billion DNA base pairs. According to the International Data Corporation, by 2020 the digital universe – the data we create and copy annually – will reach 44 zettabytes, or 44 trillion gigabytes.

image

Figure 9: The Digital Universe ( www.emc.com/leadership/digital-universe/2014iview/images )

  Doing meaningful things with data is challenging, even if we’re not dealing with millions or billions of things. In this book, we will be working with smaller sets of data. But much of what we’ll do will be applicable to very large amounts of data too.

Unit Summary

Computational Thinking is the thought processes involved in formulating a problem and expressing its solution in a way that a computer—human or machine—can effectively carry out.

Computational Thinking is what comes before any computing technology—thought of by a human, knowing full well the power of automation.

Writing a correct and valid algorithm to solve a computational problem is key to writing good code.

  • What are the inputs?
  • What are the outputs (or results)?
  • Can we break the problem into parts?
  • Think about the connections between the input & output.
  • Consider designing ‘backwards’.
  • Have you seen the problem before? In a slightly different form?
  • Can you solve part of the problem?
  • Did you use all the inputs?
  • Can you test it on a variety of inputs?
  • Can you think of how you might write the algorithm differently if you had to start again?
  • Does it solve the problem? Does it meet all the requirements? Is the output correct?
  • Does it terminate?
  • Is it general for all cases?

Practice Problems

  • Write about a process in your life (e.g. driving to the mall, walking to class, etc.) and estimate the number of steps necessary to complete the task. Would you consider this a complex or simple task? What happens if you scale that task (e.g. driving two states away to the mall)? Is your method the most efficient? Can you come up with a more efficient way?

image

  • Write an algorithm to find the average of 25 test grades out of a possible 100 points.
  • If you are given three sticks, you may or may not be able to arrange them in a triangle. For example, if one of the sticks is 12 inches long and the other two are one inch long, it is clear that you will not be able to get the short sticks to meet in the middle. For any three lengths, there is a simple test to see if it is possible to form a triangle: “If any of the three lengths is greater than the sum of the other two, then you cannot form a triangle. Otherwise, you can.”Write an algorithm that accepts three integers as arguments, and that displays either “Yes” or “No,” depending on whether you can or cannot form a triangle from sticks with the given lengths.
  • ROT13 is a weak form of encryption that involves “rotating” each letter in a word by 13 places. To rotate a letter means to shift it through the alphabet, wrapping around to the beginning if necessary, so ‘A’ shifted by 3 is ‘D’ and ‘Z’ shifted by 1 is ‘A’. Write an algorithm that accepts a word and an integer from the user, and that prints a new encrypted word that contains the letters from the original word “rotated” by the given amount (the integer input). For example, “cheer” rotated by 7 is “jolly” and “melon” rotated by −10 is “cubed.”
  • Write an algorithm which repeatedly accepts numbers until the user enters “done”. Once “done” is entered, display the total sum of all the numbers, the count of numbers entered, and the average of all the numbers.
  • Write an algorithm that sums a series of ten positive integers entered by the user excluding all numbers greater than 100. Display the final sum.
  • Wing, Jeannette M. "Computational thinking." Communications of the ACM 49.3 (2006): 33-35. ↵

how do programmers approach problem solving and coding

Privacy Policy

What exactly is a programming paradigm?

Thanoshan MV

Any fool can write code that a computer can understand. Good programmers write code that humans can understand. ― Martin Fowler

When programming, complexity is always the enemy. Programs with great complexity, with many moving parts and interdependent components, seem initially impressive. However, the ability to translate a real-world problem into a simple or elegant solution requires a deeper understanding.

While developing an application or solving a simple problem, we often say “If I had more time, I would have written a simpler program”. The reason is, we made a program with greater complexity. The less complexity we have, the easier it is to debug and understand. The more complex a program becomes, the harder it is to work on it.

Managing complexity is a programmer’s main concern . So how do programmers deal with complexity? There are many general approaches that reduce complexity in a program or make it more manageable. One of the main approaches is a programming paradigm. Let's dive into programming paradigms!

Introduction to programming paradigms

The term programming paradigm refers to a style of programming . It does not refer to a specific language, but rather it refers to the way you program.

There are lots of programming languages that are well-known but all of them need to follow some strategy when they are implemented. And that strategy is a paradigm.

The types of programming paradigms

types-of-paradigms

Imperative programming paradigm

The word “imperative” comes from the Latin “impero” meaning “I command”.

It’s the same word we get “emperor” from, and that’s quite apt. You’re the emperor. You give the computer little orders to do and it does them one at a time and reports back.

The paradigm consists of several statements, and after the execution of all of them, the result is stored. It’s about writing a list of instructions to tell the computer what to do step by step.

In an imperative programming paradigm, the order of the steps is crucial, because a given step will have different consequences depending on the current values of variables when the step is executed.

To illustrate, let's find the sum of first ten natural numbers in the imperative paradigm approach.

Example in C:

In the above example, we are commanding the computer what to do line by line. Finally, we are storing the value and printing it.

1.1 Procedural programming paradigm

Procedural programming (which is also imperative) allows splitting those instructions into procedures .

NOTE: Procedures aren't functions. The difference between them is that functions return a value, and procedures do not. More specifically, functions are designed to have minimal side effects, and always produce the same output when given the same input. Procedures, on the other hand, do not have any return value. Their primary purpose is to accomplish a given task and cause a desired side effect.

A great example of procedures would be the well known for loop. The for loop's main purpose is to cause side effects and it does not return a value.

To illustrate, let's find the sum of first ten natural numbers in the procedural paradigm approach.

In the example above, we've used a simple for loop to find the summation of the first ten natural numbers.

Languages that support the procedural programming paradigm are:

Procedural programming is often the best choice when:

  • There is a complex operation which includes dependencies between operations, and when there is a need for clear visibility of the different application states ('SQL loading', 'SQL loaded', 'Network online', 'No audio hardware', etc). This is usually appropriate for application startup and shutdown (Holligan, 2016).
  • The program is very unique and few elements were shared (Holligan, 2016).
  • The program is static and not expected to change much over time (Holligan, 2016).
  • None or only a few features are expected to be added to the project over time (Holligan, 2016).

Why should you consider learning the procedural programming paradigm?

  • It's simple.
  • An easier way to keep track of program flow.
  • It has the ability to be strongly modular or structured.
  • Needs less memory: It's efficient and effective.

1.2 Object-oriented programming paradigm

OOP is the most popular programming paradigm because of its unique advantages like the modularity of the code and the ability to directly associate real-world business problems in terms of code.

Object-oriented programming offers a sustainable way to write spaghetti code. It lets you accrete programs as a series of patches. ― Paul Graham

The key characteristics of object-oriented programming include Class, Abstraction, Encapsulation, Inheritance and Polymorphism.

A class is a template or blueprint from which objects are created.

java-oops

Objects are instances of classes. Objects have attributes/states and methods/behaviors. Attributes are data associated with the object while methods are actions/functions that the object can perform.

oop

Abstraction separates the interface from implementation. Encapsulation is the process of hiding the internal implementation of an object.

Inheritance enables hierarchical relationships to be represented and refined. Polymorphism allows objects of different types to receive the same message and respond in different ways.

To illustrate, let's find the sum of first ten natural numbers in the object-oriented paradigm approach.

Example in Java:

We have a class Addition that has two states, sum and num which are initialized to zero. We also have a method addValues() which returns the sum of num numbers.

In the Main class, we've created an object, obj of Addition class. Then, we've initialized the num to 10 and we've called addValues() method to get the sum.

Languages that support the object-oriented paradigm:

Object-oriented programming is best used when:

  • You have multiple programmers who don’t need to understand each component (Holligan, 2016).
  • There is a lot of code that could be shared and reused (Holligan, 2016).
  • The project is anticipated to change often and be added to over time (Holligan, 2016).

Why should you consider learning the object-oriented programming paradigm?

  • Reuse of code through Inheritance.
  • Flexibility through Polymorphism.
  • High security with the use of data hiding (Encapsulation) and Abstraction mechanisms.
  • Improved software development productivity: An object-oriented programmer can stitch new software objects to make completely new programs (The Saylor Foundation, n.d.).
  • Faster development: Reuse enables faster development (The Saylor Foundation, n.d.).
  • Lower cost of development: The reuse of software also lowers the cost of development. Typically, more effort is put into the object-oriented analysis and design (OOAD), which lowers the overall cost of development (The Saylor Foundation, n.d.).
  • Higher-quality software: Faster development of software and lower cost of development allows more time and resources to be used in the verification of the software. Object-oriented programming tends to result in higher-quality software (The Saylor Foundation, n.d.).

1.3 Parallel processing approach

Parallel processing is the processing of program instructions by dividing them among multiple processors.

A parallel processing system allows many processors to run a program in less time by dividing them up.

Languages that support the Parallel processing approach:

  • NESL (one of the oldest ones)

Parallel processing approach is often the best use when:

  • You have a system that has more than one CPU or multi-core processors which are commonly found on computers today.
  • You need to solve some computational problems that take hours/days to solve even with the benefit of a more powerful microprocessor.
  • You work with real-world data that needs more dynamic simulation and modeling.

Why should you consider learning the parallel processing approach?

  • Speeds up performance.
  • Often used in Artificial Intelligence. Learn more here: Artificial Intelligence and Parallel Processing by Seyed H. Roosta.
  • It makes it easy to solve problems since this approach seems to be like a divide and conquer method.

Here are some useful resources to learn more about parallel processing:

  • Parallel Programming in C by Paul Gribble
  • Introduction to Parallel Programming with MPI and OpenMP by Charles Augustine
  • INTRODUCTION TO PARALLEL PROGRAMMING WITH MPI AND OPENMP by Benedikt Steinbusch

2. Declarative programming paradigm

Declarative programming is a style of building programs that expresses the logic of a computation without talking about its control flow.

Declarative programming is a programming paradigm in which the programmer defines what needs to be accomplished by the program without defining how it needs to be implemented. In other words, the approach focuses on what needs to be achieved instead of instructing how to achieve it.

Imagine the president during the state of the union declaring their intentions for what they want to happen. On the other hand, imperative programming would be like a manager of a McDonald's franchise. They are very imperative and as a result, this makes everything important. They, therefore, tell everyone how to do everything down to the simplest of actions.

So the main differences are that imperative tells you how to do something and declarative tells you what to do .

2.1 Logic programming paradigm

The logic programming paradigm takes a declarative approach to problem-solving. It's based on formal logic.

The logic programming paradigm isn't made up of instructions - rather it's made up of facts and clauses. It uses everything it knows and tries to come up with the world where all of those facts and clauses are true.

For instance, Socrates is a man, all men are mortal, and therefore Socrates is mortal.

The following is a simple Prolog program which explains the above instance:

The first line can be read, "Socrates is a man.'' It is a base clause , which represents a simple fact.

The second line can be read, "X is mortal if X is a man;'' in other words, "All men are mortal.'' This is a clause , or rule, for determining when its input X is "mortal.'' (The symbol ":-'', sometimes called a turnstile , is pronounced "if''.) We can test the program by asking the question:

that is, "Is Socrates mortal?'' (The " ?- '' is the computer's prompt for a question). Prolog will respond " yes ''. Another question we may ask is:

That is, "Who (X) is mortal?'' Prolog will respond " X = Socrates ''.

To give you an idea, John is Bill's and Lisa's father. Mary is Bill's and Lisa's mother. Now, if someone asks a question like "who is the father of Bill and Lisa?" or "who is the mother of Bill and Lisa?" we can teach the computer to answer these questions using logic programming.

Example in Prolog:

Example explained:

The above code defines that John is Bill's father.

We're asking Prolog what value of X makes this statement true? X should be Mary to make the statement true. It'll respond X = Mary

Languages that support the logic programming paradigm:

  • ALF (algebraic logic functional programming language)

Logic programming paradigm is often the best use when:

  • If you're planning to work on projects like theorem proving, expert systems, term rewriting, type systems and automated planning.

Why should you consider learning the logic programming paradigm?

  • Easy to implement the code.
  • Debugging is easy.
  • Since it's structured using true/false statements, we can develop the programs quickly using logic programming.
  • As it's based on thinking, expression and implementation, it can be applied in non-computational programs too.
  • It supports special forms of knowledge such as meta-level or higher-order knowledge as it can be altered.

2.2 Functional programming paradigm

The functional programming paradigm has been in the limelight for a while now because of JavaScript, a functional programming language that has gained more popularity recently.

The functional programming paradigm has its roots in mathematics and it is language independent. The key principle of this paradigm is the execution of a series of mathematical functions.

You compose your program of short functions. All code is within a function. All variables are scoped to the function.

In the functional programming paradigm, the functions do not modify any values outside the scope of that function and the functions themselves are not affected by any values outside their scope.

To illustrate, let's identify whether the given number is prime or not in the functional programming paradigm.

Example in JavaScript:

In the above example, we've used Math.floor() and Math.sqrt() mathematical functions to solve our problem efficiently. We can solve this problem without using built-in JavaScript mathematical functions, but to run the code efficiently it is recommended to use built-in JS functions.

number is scoped to the function isPrime() and it will not be affected by any values outside its scope. isPrime() function always produces the same output when given the same input.

NOTE: there are no for and while loops in functional programming. Instead, functional programming languages rely on recursion for iteration (Bhadwal, 2019).

Languages that support functional programming paradigm:

Functional programming paradigm is often best used when:

  • Working with mathematical computations.
  • Working with applications aimed at concurrency or parallelism.

Why should you consider learning the functional programming paradigm?

  • Functions can be coded quickly and easily.
  • General-purpose functions can be reusable which leads to rapid software development.
  • Unit testing is easier.
  • Debugging is easier.
  • Overall application is less complex since functions are pretty straightforward.

2.3 Database processing approach

This programming methodology is based on data and its movement. Program statements are defined by data rather than hard-coding a series of steps.

A database is an organized collection of structured information, or data, typically stored electronically in a computer system. A database is usually controlled by a database management system (DBMS) ("What is a Database", Oracle, 2019).

To process the data and querying them, databases use tables . Data can then be easily accessed, managed, modified, updated, controlled and organized.

A good database processing approach is crucial to any company or organization. This is because the database stores all the pertinent details about the company such as employee records, transaction records and salary details.

Most databases use Structured Query Language (SQL) for writing and querying data.

Here’s an example in database processing approach (SQL):

The PersonID column is of type int and will hold an integer. The LastName , FirstName , Address , and City columns are of type varchar and will hold characters, and the maximum length for these fields is 255 characters.

The empty Persons table will now look like this:

Screenshot-from-2019-11-10-22-37-53

Database processing approach is often best used when:

  • Working with databases to structure them.
  • Accessing, modifying, updating data on the database.
  • Communicating with servers.

Why are databases important and why should you consider learning database processing approach?

  • Massive amount of data is handled by the database: Unlike spreadsheet or other tools, databases are used to store large amount of data daily.
  • Accurate: With the help of built-in functionalities in a database, we can easily validate.
  • Easy to update data: Data Manipulation Languages (DML) such as SQL are used to update data in a database easily.
  • Data integrity: With the help of built-in validity checks, we can ensure the consistency of data.

Programming paradigms reduce the complexity of programs. Every programmer must follow a paradigm approach when implementing their code. Each one has its advantages and disadvantages .

If you're a beginner, I would like to suggest learning object-oriented programming and functional programming first. Understand their concepts and try to apply them in your projects.

For example, if you're learning object-oriented programming, the pillars of object-oriented programming are Encapsulation, Abstraction, Inheritance and Polymorphism. Learn them by doing it. It will help you to understand their concepts on a deeper level, and your code will be less complex and more efficient and effective.

I strongly encourage you to read more related articles on programming paradigms. I hope this article helped you.

Please feel free to let me know if you have any questions.

You can contact and connect with me on Twitter @ThanoshanMV .

Thank you for reading.

Happy Coding!

  • Akhil Bhadwal. (2019). Functional Programming: Concepts, Advantages, Disadvantages, and Applications
  • Alena Holligan. (2016). When to use OOP over procedural coding
  • The Saylor Foundation. (n.d.). Advantages and Disadvantages of Object-Oriented Programming (OOP)
  • What is a Database | Oracle. (2019).

System.out.println("Hey there, I am Thanoshan!");

If this article was helpful, share it .

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

How to solve coding problems step by step – Complete guide self.__wrap_b=(t,n,e)=>{e=e||document.querySelector(`[data-br="${t}"]`);let a=e.parentElement,r=R=>e.style.maxWidth=R+"px";e.style.maxWidth="";let o=a.clientWidth,c=a.clientHeight,i=o/2-.25,l=o+.5,u;if(o){for(;i+1 {self.__wrap_b(0,+e.dataset.brr,e)})).observe(a):process.env.NODE_ENV==="development"&&console.warn("The browser you are using does not support the ResizeObserver API. Please consider add polyfill for this API to avoid potential layout shifts or upgrade your browser. Read more: https://github.com/shuding/react-wrap-balancer#browser-support-information"))};self.__wrap_b(":R4mr36:",1)

Mehul Mohan's profile image

Understand the Problem Statement

Choose the right data structure and algorithm, write pseudocode, implement the solution, test your solution, optimize and refactor, learning from others, asking for help, practice, practice, practice.

How to solve coding problems step by step – Complete guide

As a developer, solving coding problems is an essential skill that not only helps you understand complex algorithms and data structures but also allows you to tackle real-world challenges in domains like web development and mobile app development. In this blog post, we will discuss various ways to solve coding problems step by step and share some resources to help you master this skill. Let's dive in!

The first and most important step in solving any coding problem is to understand the problem statement. Read the instructions carefully and make sure you fully comprehend the requirements. Break down the problem into smaller, manageable tasks and try to visualize the expected input and output.

Once you have a clear understanding of the problem, it's time to choose the right data structure and algorithm to solve it. This requires a strong foundation in data structures and algorithms, as well as knowledge about their time and space complexities. To improve your understanding of various data structures and algorithms, you can visit the official codedamn website to find a wealth of resources, including tutorials, videos, and practice problems.

Before jumping into writing actual code, it's a good idea to write down the algorithm in pseudocode. Pseudocode is a plain-text representation of the steps involved in solving the problem, which helps you organize your thoughts and identify potential issues before you start coding.

Now that you have a clear roadmap in the form of pseudocode, it's time to implement the solution in your preferred programming language. Begin by setting up the required data structures and variables, and then follow the algorithm outlined in your pseudocode. Make sure to write clean and efficient code, and don't forget to add comments to explain the logic behind your implementation.

After implementing the solution, it's crucial to test it against various test cases to ensure its correctness and efficiency. Start by testing your solution against the provided examples and then move on to edge cases and other scenarios that could potentially cause your solution to fail. If you encounter any issues, debug your code and make the necessary adjustments.

Once you have a working solution, it's time to optimize and refactor your code. Look for opportunities to improve the efficiency of your solution by using more efficient algorithms or data structures. Additionally, consider refactoring your code to make it more readable and maintainable.

One of the best ways to improve your problem-solving skills is by learning from others. Websites like LeetCode and Codeforces provide a platform for developers to share their solutions and discuss different approaches to solving coding problems. By analyzing other people's solutions, you can gain insights into alternative methods and improve your own problem-solving abilities.

If you're stuck on a coding problem, don't hesitate to ask for help. Online communities like Stack Overflow and Reddit are great places to seek guidance and advice from experienced developers. Remember to provide a clear explanation of the problem, your current approach, and any specific issues you're facing when asking for help.

Finally, the key to becoming a proficient problem solver is consistent practice. Regularly challenge yourself with new coding problems and work to improve your understanding of data structures, algorithms, and programming techniques. With time and dedication, you'll find that tackling complex coding problems becomes second nature.

Q: How do I improve my problem-solving skills?

A: Practice regularly, learn from others, and study data structures and algorithms. Websites like codedamn, LeetCode, and Codeforces are excellent resources for practicing and learning from others.

Q: What should I do if I'm stuck on a coding problem?

A: Don't be afraid to ask for help. Online communities like Stack Overflow and Reddit are great places to seek guidance from experienced developers. Make sure to provide a clear explanation of the problem, your current approach, and any specific issues you're facing.

Q: How can I choose the right data structure and algorithm for a problem?

A: Understanding the problem statement and having a strong foundation in data structures and algorithms are crucial for choosing the right solution. Consider the time and space complexities of different approaches and choose the one that best meets the problem's requirements.

Q: How important is it to write pseudocode before implementing a solution?

A: Writing pseudocode can help you organize your thoughts and identify potential issues before you start coding, making it an essential step in the problem-solving process.

Q: How can I optimize and refactor my code?

A: Look for opportunities to improve the efficiency of your solution by using more efficient algorithms or data structures. Additionally, consider refactoring your code to make it more readable and maintainable.

Sharing is caring

Did you like what Mehul Mohan wrote? Thank them for their work by sharing it on social media.

No comment s so far

how do programmers approach problem solving and coding

Member-only story

10 Steps to Solving a Programming Problem

Tips for new developers staring at a blank screen, unsure of where to start.

Valinda Chan

Valinda Chan

Some of the feedback I hear from new developers working on a programming problem revolves around uncertainty of where to start. You understand the problem, the logic, basics of the syntax, etc. If you see someone else’s code or have someone to guide you, you can follow along. But maybe you feel uncertain about doing it yourself and have trouble turning your thoughts into code at first even though you understand the syntax or logic. Here’s my process and some tips to tackling a sample problem that hopefully some of you may find helpful in your journey.

1. Read the problem at least three times (or however many makes you feel comfortable)

You can’t solve a problem you don’t understand. There is a difference between the problem and the problem you think you are solving. It’s easy to start reading the first few lines in a problem and assume the rest of it because it’s similar to something you’ve seen in the past. If you are making even a popular game like Hangman, be sure to read through any rules even if you’ve played it before. I once was asked to make a game like Hangman that I realized was “Evil Hangman” only after I read through the instructions (it was a trick!).

Sometimes I’ll even try explaining the problem to a friend and see if her understanding of my explanation matches the problem I am tasked with. You don’t want to find out halfway through that you misunderstood the problem. Taking extra time in the beginning is worth it. The better you understand the problem, the easier it will be to solve it.

Let’s pretend we are creating a simple function selectEvenNumbers that will take in an array of numbers and return an array evenNumbers of only even numbers. If there are no even numbers, return the empty array evenNumbers .

Here are some questions that run through my mind:

  • How can a computer tell what is an even number? Divide that number by 2 and see if its remainder is 0.
  • What am I passing into this function? An array
  • What will that array contain? One or more numbers
  • What are the data types of the elements in the array? Numbers
  • What is the goal of this function? What am I returning at the end of this function? The goal is to take all the even numbers and return them in an array. If there are no even numbers, return an empty array.

2. Work through the problem manually with at least three sets of sample data

Take out a piece of paper and work through the problem manually. Think of at least three sets of sample data you can use. Consider corner and edge cases as well.

Corner case : a problem or situation that occurs outside of normal operating parameters, specifically when multiple environmental variables or conditions are simultaneously at extreme levels, even though each parameter is within the specified range for that parameter. Edge case : problem or situation that occurs only at an extreme (maximum or minimum) operating parameter

For example, below are some sets of sample data to use:

When you are first starting out, it is easy to gloss over the steps. Because your brain may already be familiar with even numbers, you may just look at a sample set of data and pull out numbers like 2 , 4 , 6 and so forth in the array without fully being aware of each and every step your brain is taking to solve it. If this is challenging, try using large sets of data as it will override your brain’s ability to naturally solve the problem just by looking at it. That helps you work through the real algorithm.

Let’s go through the first array [1]

  • Look at the only element in the array [1]
  • Decide if it is even. It is not
  • Notice that there are no more elements in this array
  • Determine there are no even numbers in this provided array
  • Return an empty array

Let’s go through the array [1, 2]

  • Look at the first element in array [1, 2]
  • Look at the next element in the array
  • Decide if it is even. It is even
  • Make an array evenNumbers and add 2 to this array
  • Return the array evenNumbers which is [2]

I go through this a few more times. Notice how the steps I wrote down for [1] varies slightly from [1, 2] . That is why I try to go through a couple of different sets. I have some sets with just one element, some with floats instead of just integers, some with multiple digits in an element, and some with negatives just to be safe.

3. Simplify and optimize your steps

Look for patterns and see if there’s anything you can generalize. See if you can reduce any steps or if you are repeating any steps.

  • Create a function selectEvenNumbers
  • Create a new empty array evenNumbers where I store even numbers, if any
  • Go through each element in the array [1, 2]
  • Find the first element
  • Decide if it is even by seeing if it is divisible by 2. If it is even, I add that to evenNumbers
  • Find the next element
  • Repeat step #4
  • Repeat step #5 and #4 until there are no more elements in this array
  • Return the array evenNumbers , regardless of whether it has anything in it

This approach may remind you of Mathematical Induction in that you:

  • Show it is true for n = 1 , n = 2 , ...
  • Suppose it is true for n = k
  • Prove it is true for n = k + 1

4. Write pseudocode

Even after you’ve worked out general steps, writing out pseudocode that you can translate into code will help with defining the structure of your code and make coding a lot easier. Write pseudocode line by line. You can do this either on paper or as comments in your code editor. If you’re starting out and find blank screens to be daunting or distracting, I recommend doing it on paper.

Pseudocode generally does not actually have specific rules in particular but sometimes, I might end up including some syntax from a language just because I am familiar enough with an aspect of the programming language. Don’t get caught up with the syntax. Focus on the logic and steps.

For our problem, there are many different ways to do this. For example, you can use filter but for the sake of keeping this example as easy to follow along as possible, we will use a basic for loop for now (but we will use filter later when we refactor our code).

Here is an example of pseudocode that has more words:

Here is an example of pseudocode that has fewer words:

Either way is fine as long as you are writing it out line-by-line and understand the logic on each line.

Refer back to the problem to make sure you are on track.

5. Translate pseudocode into code and debug

When you have your pseudocode ready, translate each line into real code in the language you are working on. We will use JavaScript for this example.

If you wrote it out on paper, type this up as comments in your code editor. Then replace each line in your pseudocode.

Then I call the function and give it some sample sets of data we used earlier. I use them to see if my code returns the results I want. You can also write tests to check if the actual output is equal to the expected output.

I generally use console.log() after each variable or line or so. This helps me check if the values and code are behaving as expected before I move on . By doing this, I catch any issues before I get too far. Below is an example of what values I would check when I am first starting out. I do this throughout my code as I type it out.

After working though each line of my pseudocode, below is what we end up with. // is what the line was in pseudocode. Text that is bolded is the actual code in JavaScript.

I get rid of the pseudocode to avoid confusion.

Sometimes new developers will get hung up with the syntax that it becomes difficult to move forward. Remember that syntax will come more naturally over time and there is no shame in referencing material for the correct syntax later on when coding.

6. Simplify and optimize your code

You’ve probably noticed by now that simplifying and optimizing are recurring themes.

“Simplicity is prerequisite for reliability.” — Edsger W. Dijkstra, Dutch computer scientist and early pioneer in many research areas of computing science

In this example, one way of optimizing it would be to filter out items from an array by returning a new array using filter . This way, we don’t have to define another variable evenNumbers because filter will return a new array with copies of elements that match the filter. This will not change the original array. We also don’t need to use a for loop with this approach. filter will go through each item, return either true , to have that element in the array, or false to skip it.

Simplifying and optimizing your code may require you to iterate a few times, identifying ways to further simplify and optimize code.

Here are some questions to keep in mind:

  • What are your goals for simplifying and optimizing? The goals will depend on your team’s style or your personal preference. Are you trying to condense the code as much as possible? Is the goal to make it the code more readable? If that’s the case, you may prefer taking that extra line to define the variable or compute something rather than trying to define and compute all in one line.
  • How else can you make the code more readable?
  • Are there any more extra steps you can take out?
  • Are there any variables or functions you ended up not even needing or using?
  • Are you repeating some steps a lot? See if you can define in another function.
  • Are there better ways to handle edge cases?
“Programs must be written for people to read, and only incidentally for machines to execute.” — Gerald Jay Sussman and Hal Abelson, Authors of “Structure and Interpretation of Computer Programs”

This step really should be throughout the process. Debugging throughout will help you catch any syntax errors or gaps in logic sooner rather than later. Take advantage of your Integrated Development Environment (IDE) and debugger. When I encounter bugs, I trace the code line-by-line to see if there was anything that did not go as expected. Here are some techniques I use:

  • Check the console to see what the error message says. Sometimes it’ll point out a line number I need to check. This gives me a rough idea of where to start, although the issue sometimes may not be at this line at all.
  • Comment out chunks or lines of code and output what I have so far to quickly see if the code is behaving how I expected. I can always uncomment the code as needed.
  • Use other sample data if there are scenarios I did not think of and see if the code will still work.
  • Save different versions of my file if I am trying out a completely different approach. I don’t want to lose any of my work if I end up wanting to revert back to it!
“The most effective debugging tool is still careful thought, coupled with judiciously placed print statements.” — Brian W. Kernighan, Computer Science Professor at Princeton University

8. Write useful comments

You may not always remember what every single line meant a month later. And someone else working on your code may not know either. That’s why it’s important to write useful comments to avoid problems and save time later on if you need to come back to it.

Stay away from comments such as:

// This is an array. Iterate through it.

// This is a variable

I try to write brief, high-level comments that help me understand what’s going on if it is not obvious. This comes in handy when I am working on more complex problems. It helps understand what a particular function is doing and why. Through the use of clear variable names, function names, and comments, you (and others) should be able to understand:

  • What is this code for?
  • What is it doing?

9. Get feedback through code reviews

Get feedback from your teammates, professors, and other developers. Check out Stack Overflow . See how others tackled the problem and learn from them. There are sometimes several ways to approach a problem. Find out what they are and you’ll get better and quicker at coming up with them yourself.

“No matter how slow you are writing clean code, you will always be slower if you make a mess.” — Uncle Bob Martin, Software Engineer and Co-author of the Agile Manifesto

10. Practice, practice, practice

Even experienced developers are always practicing and learning. If you get helpful feedback, implement it. Redo a problem or do similar problems. Keep pushing yourself. With each problem you solve, the better a developer you become. Celebrate each success and be sure to remember how far you’ve come. Remember that programming, like with anything, comes easier and more naturally with time.

“Take pride in how far you’ve come. Have faith in how far you can go. But don’t forget to enjoy the journey.” — Michael Josephson, Founder of Joseph and Edna Josephson Institute of Ethics

Thanks Gavin Stark

Valinda Chan

Written by Valinda Chan

Product & UX Design

More from Valinda Chan and codeburst

Leading with the Power of Influence vs. Positional Power

ThinkGrowth.org

Leading with the Power of Influence vs. Positional Power

Getting people to take risks in a risk-averse environment.

How To Create Horizontal Scrolling Containers

How To Create Horizontal Scrolling Containers

As a front end developer, more and more frequently i am given designs that include a horizontal scrolling component. this has become….

Top 50 Java Interview Questions for Beginners and Junior Developers

Top 50 Java Interview Questions for Beginners and Junior Developers

A list of frequently asked java questions and answers from programming job interviews of java developers of different experience..

Getting it right: why infographics are not the same as data visualizations

Getting it right: why infographics are not the same as data visualizations

A rundown on the key differences and ideas for when to use each, recommended from medium.

Advice From a Software Engineer With 8 Years of Experience

Benoit Ruiz

Better Programming

Advice From a Software Engineer With 8 Years of Experience

Practical tips for those who want to advance in their careers.

How I Create Passive Income With No Money

Hazel Paradise

How I Create Passive Income With No Money

Many ways to start a passive income today.

how do programmers approach problem solving and coding

General Coding Knowledge

how do programmers approach problem solving and coding

Stories to Help You Grow as a Software Developer

how do programmers approach problem solving and coding

Coding & Development

how do programmers approach problem solving and coding

ChatGPT prompts

The Era of High-Paying Tech Jobs is Over

Somnath Singh

Level Up Coding

The Era of High-Paying Tech Jobs is Over

The death of tech jobs..

What Happens When You Start Reading Every Day

Sufyan Maan, M.Eng

ILLUMINATION

What Happens When You Start Reading Every Day

Think before you speak. read before you think. — fran lebowitz.

The guide to Git I never had.

The guide to Git I never had.

🩺 doctors have stethoscopes..

I Tried Upwork For 30 Days

Hammad Hassan

I Tried Upwork For 30 Days

I challenged myself to earn $100 in the first month, and it turned out earning more than that..

Text to speech

Beta Get $5 off your first Resume Review with a Recruiter or Expert from your target company →

7 Tips on How to Approach and Solve Coding Problems Successfully

author profile pic

If you hope to excel at writing code and land the job of your dreams, you should begin with building your problem-solving abilities.

tips on how to solve coding problems in interviews

Proficiency in software development is often associated with the ability to write complex codes in a short span of time. However, in practice, the field is as much about critical analysis and communication as it is about tackling coding challenges quickly and efficiently. At its core, software programming essentially means to solve problems. It teaches you to think analytically and determine the best possible solution to a problem — something that is common among all successful software developers. 

So, if you hope to excel at writing code and land the job of your dreams, you should begin with building your problem-solving abilities. In this article, we will provide you with 7 proven tips to approach problems so you get better at coding. So, let’s get started with the first one!

LAUNCH your dream career!

Talk to a coach from your target company for:

  • Mock Interviews
  • Negotiation
  • Resume Reviews
  • Expert Advice

Relevant Guides

1. get out of your comfort zone.

You should be well-versed with the underlying logic of algorithms so as to determine optimal solutions to coding problems. So, begin with brushing up on basic data structures and algorithms, and developing in-depth understanding of core conceits. It is recommended that you take it slow; increase the difficulty level of your learning and coding gradually. In any case, do not directly jump onto something advanced without learning the basics. 

You should also ensure that you don't get comfortable with executing codes using just one approach. The idea is to familiarize yourself with different problem-solving techniques to build your coding skills. One way to do this is to solve a variety of coding problems on challenging coding platforms like HackerRank, HackerEarth, Codewars, GitHub, to name a few. This will force you to be flexible, and employ the best possible framework for every problem.

Watch these videos

2. break the problem into parts.

It helps if you break the large and complex problem into sections and address them part by part. This will help you write simple and efficient codes devoid of any unnecessary complexities. 

Here's what you can do:

  • Create a flow chart illustrating the problem.
  • Break it into subproblems or smaller sections.
  • Solve each section by creating independent functions.
  • Arrange the functions in the order you need, thereby merging them all for the final solution. 
  • In case of errors, you can debug the code and search for an alternate approach. 

You can draw up the pseudo code and run it logically before replacing it with the original code. A pseudocode provides clarity on the requirements and functioning of the code, and thus makes writing the actual code easier. So, don't make the mistake of skipping this step. 

Read these articles

3. optimize your code for efficiency.

While there are a ton of programming algorithms and data structures to help you write codes, you should be able to choose the right software for optimised coding; hardware can not compensate for inefficiencies that arise due to incorrect algorithms and data structures. 

This is where time and space complexity, and stability come into the picture. For instance, the selection sort may not be the recommended for larger lists, it is highly efficient to sort smaller lists. Similarly, binary search is considered to be the quickest and most efficient search algorithm; however, linear search or breadth-first search also have their distinct advantages. 

So, given a problem, ask yourself, which sorting method is best suited for your input? Is it possible to eliminate nested loops? Does this search method provide a performance advantage? 

Examine the solution code thoroughly while simultaneously paying close attention to the time and space complexity. Determine if arrays, strings, binary trees, sorting, or loops are best suited to attain your goal. 

Run your code through edge cases by feeding empty or unacceptable inputs so you become aware of boundary conditions. LeetCode is an excellent platform when looking for coding problems to solve optimally. 

4. Learn from the past

Simply finding a solution to a coding problem should not be your primary goal; you should actively revisit your old codes to incorporate new concepts you've learned, eliminate redundant processes, if any, and optimize your code for performance and efficiency, thereby laying the groundwork for improvement. Ask yourself: 

  • Does the solution code run for all possible inputs?
  • Are there any alternate solutions  to the problem code?
  • How do I improve the performance and efficiency of the code? Is it possible to reduce the code space and compilation time? 
  • How can I make the code more readable? What are the redundant steps that can be struck out?

As you familiarize yourself with useful patterns or problems you faced in the past while solving coding questions, you'll succeed in building yourself a toolkit of solutions to apply to new problems. Learning about the flaws in your code helps you grow as a developer. 

5. Let feedback guide you towards improvement

Sometimes, all you need is a fresh set of your eyes to realign your coding perspective. So, don't hesitate to seek help from friends or colleagues if you are facing problems with your code. Your peers may have a better or more optimized framework that you aren't aware of. Allow them to teach you so as to hone your problem solving with algorithms and data structures. This is your best chance to refine your methodologies and get better at coding problems.

Make sure you return the favour if the opportunity ever presents itself. In this manner, you can collectively progress your coding abilities. 

6. Resist the temptation to look up for solution

If you are stuck somewhere, look up the solution code only as a last resort. When you do, you are likely to find a specific framework to solve the problem which in turn will serve to disrupt your individualistic problem-solving abilities. So, resist the temptation to look up the solution wherever possible. Think hard and try to arrive at the solution on your own. 

Even if you do go down that road, such as by using a tool like chatgpt , avoid memorizing or taking it down as is; simply familiarize yourself with the logic and attempt to create a new solution based on your learning. 

7. Practice, Practice, Practice

If there's one sure shot way of getting better at coding problems, it is to practice until you become confident of your problem-solving skills. From brushing up on data structures like arrays, strings, trees, linked lists, and heaps to building competence in search, sort, time complexity algorithms, the end goal is to be able to visualize optimized, logical solutions to any given coding problem. 

Make sure to time yourself so you get a taste of the kind of pressure you'll be expected to tackle at your technical interview. 

You can participate in coding challenges or hackathons so as to assert your readiness. This will also help you find out where your weaknesses lie, and allow you to work towards eliminating them.

Other problem-solving activities you can indulge in on the side are puzzle games, chess, riddles to boost critical and analytical thinking capacities.

Mastering coding is no easy feat. It takes dedicated effort and time. So, don’t beat yourself up if you face obstacles along the way. Just make sure you keep at it, and you will eventually excel at problem solving with algorithms and data structures. We hope this helped you understand how you can get better at coding! 

7-Step Approach to Solve Any Coding Problem (Important for Interviews)

Discover the comprehensive 7-step strategy to conquer coding problems in interviews. Learn how to understand, plan, code, debug, optimize, and present your solutions effectively.

Kishan Pandey

Kishan Pandey

The capability to approach hard problems confidently is a quality that can set you apart in the fast-paced world of coding interviews. Whether you're a seasoned programmer or just starting out, developing your problem-solving skills is imperative.

Welcome to a thorough manual that reveals a 7-step process for resolving any coding issue, a goldmine of knowledge created to help you conquer those technical interviews with grace. From understanding the problem to presenting your solution, we'll walk you through each step, equipping you with the knowledge and strategies needed to excel in the coding interview arena. Let's dive in and unlock the secrets to becoming a coding problem-solving virtuoso.

So, you’ve been given a problem in a coding interview for the company you have ever so wanted to be a part of, and for the same reason you feel nervous and you can’t find a way. You feel stuck, your lips drying and your palms sweating.

“But, I’ve solved such questions a hundred times before”. We know that. And that’s how coding can be, you’ve solved something 100 times but you can get stuck the 101st time. What do you do about it, then?

How can you ensure that you don’t falter in critical situations and solve those problems with impeccable consistency?

You can do that by clearing all the clutter and following a streamlined approach to solving problems. Now, there’s a 100% chance that you already follow a certain process subconsciously and get results out of it. But, in important moments your mind can get blurred and you might end up scratching your head.

Thus, it's important to have a process in your conscious mind, so, when the time comes you know what roadmap to take instead of feeling all fidgety.

And that’s why we have laid down a bullet-proof roadmap for you to approach any programming problem the right way and end up solving most problems at hand. It’ll help you in visualizing the solution and optimize for time and space complexity, not just in coding interviews but in general.

Make Sense of the Problem and Analyze

Before diving into coding, make sure you fully comprehend the problem statement. Break it down into simpler components and clarify any doubts. A deep understanding is the foundation for a successful solution.

It can be tempting to jump straight into coding and break that time barrier when given a problem. However, that’s the wrong approach more often than not.

Understanding the problem comes first and foremost. By understanding, we mean:

  • Making sure that you have enough information
  • Would you be able to explain the question to someone in a layman’s way?
  • Can you deduce what and how many inputs are required?
  • What would be the output for those inputs?

Remember, a war starts with strategy, not on the battlefield.

Clarify any sections of the problem that are unclear as you read through it. You can do this during an interview by asking the interviewer to describe the problem.

A doodle showing how to understand problems better

Incorporate system thinking into your problem-solving.

Systems thinking approach recognizes that a whole is greater than its parts — that all the aspects of a problem connect, interact, and influence results.

Have you ever encountered someone who sees things from a 10,000-foot perspective? They focus on the bigger picture rather than the specifics, and they are skilled at assessing situations before taking action. These people are most likely good "systems thinkers."

Visualize the problem using pen and paper

Consider different approaches to solving the problem. Choose the one that seems most efficient and scalable. Outline your solution on paper or in your mind, including algorithms and data structures.

Have you ever wondered why videos demonstrating the solutions to coding challenges often use diagrams and why coding interviews are typically conducted on whiteboards?

That’s because whiteboards allow you to draw diagrams which hugely benefits problem-solving.

Understanding how the internal state of a program changes is a significant aspect of coding, and diagrams are incredibly helpful tools for representing the internal state of data structures. Create a visual depiction of the problem and, if necessary, the internal states at each stage if you are having trouble understanding how the solution is reached.

The same can be true about code. The goal of handwriting code is to work through logic ahead of time. In design, there is a desire to "get in the browser" as quickly as possible, but there is a pearl of conventional wisdom in hand-drawing designs. A low-fidelity medium facilitates speedy experimentation and low-cost errors.

Formulating algorithm using pen and paper

If the input consists of trees, graphs, matrices, or linked lists, this technique is particularly helpful.

Break down the problem

Instead of being intimidated and becoming confused by a complex or large coding question, it is better to break it down into smaller pieces and then attempt to solve each component individually. The actions you should take to answer the challenging coding questions are listed below:

  • Create a UML diagram or a flowchart for the problem at hand
  • Separate the issue into smaller issues or parts
  • Address the smaller issues. Create separate functions for every subproblem
  • Call the solutions to each subproblem in the correct order or as necessary to connect them
  • Use classes and objects whenever necessary for handling questions (for real-world problems like management systems, etc.)

Breaking down a problem into sub problems

Use Sample Inputs and Examples thoroughly

Taking more examples and working through some sample inputs can help you grasp the issue better. It will also help you determine how many different scenarios your code should cover and what kinds of outputs or output ranges are possible.

Here is what we would recommend:

  • Use extremely basic examples to determine the results.
  • Increase the complexity and size of the inputs to determine the output and the desired number of use cases.

Now is the time to handle ‘edge cases’

  • Try solving the issue without any input; what should the result be?
  • Try the issue with invalid input and see what the result should be

Edge case- An edge case in programming often contains input values that require specific handling in an algorithm behind a computer program. In such circumstances, unit tests are typically created as a measure for validating the behaviour of computer programs; they test the boundary conditions of an algorithm, function, or method.

Depicting an edge case with Chess

Write the Pseudocode

Pseudocode is a high-level description of your solution using plain language. It helps you organize your thoughts before writing actual code. Ensure your pseudocode is clear and easy to understand.

The next step would be to write your devised plan in pseudo-code.

What’s a pseudo code?

Pseudocode is a straightforward explanation of an algorithm's steps. In other words, your pseudocode is your step-by-step strategy for resolving the issue.

Outline the steps you must take to resolve the issue in writing. There would be more steps if the issue were more complex.

For now, let’s take a simple problem as an example:

“Create a function that adds together two numbers and returns that value.”

For this problem, your pseudo code might go something like this-

  • // Create a sum variable.
  • Add the first input to the second input using the addition operator.
  • // Store values of both inputs into the sum variable.
  • // Return as output the sum variable.

This would be the step-by-step plan to reach the solution. Even if you encounter more complex cases, think of how a human solves problems systematically. What we often forget is that the working solution is just the code version of the manual approach we take.

You can create the code for an approach if you can identify a certain set of guidelines that apply to every example. Even while you might not find the best solution by doing this, it's a start and will earn you some points.

Start Coding

Start writing your code incrementally, focusing on small sections at a time. Test each part thoroughly to catch errors early. Use comments to explain complex logic and your thought process.

It's time to convert the pseudocode you just wrote into actual code.

Each line of your pseudocode should be replaced with actual code written in the language you are learning. If your difficulty has been broken down into smaller problems, note the code for each smaller problem. Keep these three things in mind when you write the code:

  • The point where you first started
  • Where are you at this moment?
  • What is your goal or intended outcome?

Also, keep in mind to focus on just the coding part at this step. You might think like- ‘What if it turns out to be inefficient code?’ But you don’t have to think of optimizing for now in case of a complex problem. You can always get to that later.

When participating in an interview, avoid wasting time by first finding out the entire solution before sharing it with the interviewer. Instead, keep the problem simple while sharing your strategy instead.

  • Describe your starting point to the interviewer.
  • Describe the strategy you have in mind right now.

You must have heard this in several places and by several experts that interviews are more interested in knowing your approach to the challenge. And that’s absolutely true.

If you find a part that is really difficult, ignore that for a while and continue solving the simpler sub-parts. This will give you the time to reflect on the challenging area; and finally, you can try applying a similar strategy to the challenging part. It works.

Optimize your code

Always strive to make your code better. Consider the past, reevaluate the situation, and look for a superior or different answer. You should aim to produce the proper quantity of good code, as we previously discussed, so always look for a different solution that is more effective than the original.

The final step you should take is not to just write the right answer to your problem. Write out the most effective or optimized solution for your code after thoroughly exploring all potential answers to the problem.

Code Optimization Technique

Following are some questions you should ask yourself once you have finished developing the solution to your code:

  • Does this code work for all input scenarios, including the edge cases?
  • Can there be a different approach to the same problem?
  • Is the coding productive? Can the performance be enhanced or made more effective?
  • How else could the code be made to be more readable?
  • Are there any additional stages or tasks you can eliminate?
  • Is your code repetitive in any way? Get rid of it.

And voila! You would have successfully solved the problem in most cases if you follow the process correctly.

Applying the same process in problem after problem will set a default method in your mind and coding will get much faster and more effective over time.

We hope you were able to grasp the step-by-step process of taking on a coding problem.

If you're an aspiring programmer striving to build a scalable career in the tech industry, check out our full-time and part-time courses in full-stack web development , offered at zero upfront fee.

And if you're already a working professional and want to elevate your career and salary to new heights, we've got you covered as well. Check out the Masai X - Backend Development Course and pay for the program only if you get placed for a CTC of INR 10 LPA.

What's the importance of understanding the problem before coding?

Understanding the problem is crucial because it forms the basis for any effective coding solution. Without a clear grasp of the problem statement, you may end up creating inefficient or incorrect code. Proper understanding allows you to break the problem into manageable components, select the right algorithms, and design an efficient solution.

Why is code optimization important in the problem-solving process?

Code optimization is essential to enhance the efficiency and performance of your solution. In interviews, interviewers often evaluate not just the correctness of your code but also its efficiency. Optimized code can reduce time and space complexity, making it more scalable and effective. It showcases your ability to think critically and produce high-quality code, which can be a significant advantage during technical interviews.

Our Courses

Practice-Based Learning Tracks, Supercharged By A.I.

how do programmers approach problem solving and coding

  • Prep Courses
  • Coding Questions
  • Behavioral Questions
  • Build Your Portfolio
  • Goal-Setting
  • Productivity
  • Start a Blog
  • Software Engineer
  • Game Development
  • Blockchain Developer
  • Cloud Computing
  • Web3 Developer
  • The Complete Software Developer’s Career Guide
  • 10 Steps to Learn Anything Quickly
  • How to Market Yourself as a Software Developer
  • Create a Blog That Boosts Your Career
  • 10 Ways to Make Money From Your Blog
  • Best Coding Hardware
  • Blockchain Languages

How to Solve Programming Problems

Text Only 02

Written By John Sonmez

Right before the holidays, I said that you had better learn how to solve programming problems .

This time I am going to try and give you some good tools to enable you to get good at solving programming problems.  (Really algorithm type problems specifically.)

Common mistakes

lolcatthink

When most programmers are given a programming problem in an interview, they make several key mistakes.  The most severe of those is the improper allocation of time.

If you have heard the saying “measure twice and cut once,” then you are probably familiar with the idea of spending upfront time to make sure something is done right, rather than diving right in.

The most common mistake I see when conducting interviews or watching someone try to solve a programming problem is they try to start writing code as soon as possible.

You must resist this urge.

You really want to make sure you take enough time to understand the problem completely before attempting to solve it.

Another big mistake is trying to over solve the solution on the first iteration.  Keep it simple, don’t try to get fancy.

A simple set of steps

I am going to give you a simple set of steps to follow which you can use for any algorithm type programming problem.

  • Read the problem completely twice.
  • Solve the problem manually with 3 sets of sample data.
  • Optimize the manual steps.
  • Write the manual steps as comments or pseudo-code.
  • Replace the comments or pseudo-code with real code.
  • Optimize the real code.

As much as 70% of our time should be spent in steps 1-3.

Let’s look at each step.

Read the problem completely twice

This is the single most important step.  You may even want to read the problem 3 or 4 times.

You want to make sure you completely understand the problem.  A good test of this is whether or not you can explain the problem to someone else.

I cannot over-emphasize how important this step is!

If you don’t understand the problem, you cannot solve it.  Do not worry about wasting time here, because the better you understand the problem, the easier it will be to solve it.

If you are given any examples along with the problem, make sure you have worked through the examples and understand why the answers are correct for each one.

Solve the problem manually

“Nothing can be automated that cannot be done manually!”

Programming is automation plain and simple.  You may have the ability to skip the manual steps and jump directly to code, but there is a manual process which is the foundation of any code you write.

It is very important to solve the problem manually first, so that you know what you are going to automate, otherwise you are just slinging code around.  Which while can be fun, will make you look like an idiot in a programming interview and will probably cause you to sweat profusely.

I recommend that you solve the problem with at least three different inputs to make sure you really understand your solution and that it will work for more than one case.

I often use a Mathematical Induction approach if possible.  Using this approach I might try and solve for 1 first, then for 2, then for n.

Also don’t forget to look for corner cases and edge cases and do any examples for those kind of cases you can think of.

It’s very important that when you solve a problem manually, you recognize what your brain is actually doing to solve the problem.  You may need to write out all the things you are normally storing in your head.  You want to be aware of each step, it is easy to gloss over them.

Let’s look at a very basic example, reversing a string.

If I give you a string “Zebra”, and ask you to reverse it, most people will do the following manual steps.

  • Write “Zebra” down.
  • Start a new word, and put “a” as the first letter.  (Why –> because it is the last letter, we want to start here)
  • Put “r” down as the 2nd letter.  (Why –> because it is the next letter backwards from the last letter we copied)
  • Put “b” down as the 3rd letter.  (Why –> same as above)

Notice how I write down each little step and why.

Optimize the manual solution

People often don’t realize how valuable this step is.  It is much easier to rearrange and reconstruct and idea or algorithm in your head than it is in code.

It’s well worth the effort to try and optimize the actual solution or simplify it when it is still in the most easily malleable state.

What you want to do here is figure out if there is another way you can solve the problem easier, or if there are some steps you can cut our or simplify.

Let’s look at our string reversal example and see if we can simplify the steps.

We should be able to immediately recognize that we can use a loop here to reduce the manual steps.  Our duplicate why’s for most of our steps tell us that we are doing the same thing over and over for each step, just with different data.

  • Start at the last letter in the word and create a new empty word.
  • Append the current letter to the new word
  • If there is a previous letter, make the previous letter the current letter and start back at 3.

Look how close we are getting to code at this point.  You should be tempted to actually write the code for this.  That is good, it tells you that you have solved and simplified the problem well.  Writing code should now become very easy.

Write pseudo-code or comments

Many times you can skip this step if you have a really good handle on the problem or your previous steps already created a detailed enough description of the solution that coding it is already a 1 to 1 translation.

If you are a beginner or struggle with these kinds of problems, I would go ahead and take the time to do this step anyway though.

What we want to do here is capture all the steps we created and now either put them into our editor as comments or write them as psuedo-code that we can translate to real code.

By doing this, we can know exactly what the structure of the code we are going to write is going to look like which makes the job of filling in the actual code later trivial.

Let’s look at some psudeo-code for reversing a string.

// NewWord = “” // Loop backwards through word to reverse //   NewWord += CurrentLetter // Return NewWord

Pretty simple, but the key thing we have done here is outlined the structure of the code we will write to solve the problem.

Replace comments with real code

This step should be extremely easy at this point.  If you have done all the other steps, this step involves no problem solving at all.

All we do here is take each comment and convert it into a real line of code.

Taking the string reversal, we might end up with something like this.

1 for 1 translation of the comments we created above for real code.

If you struggle here, there are usually two possible reasons:

  • You didn’t break down the problem into small enough steps
  • You don’t know your programming language well enough to do the conversion

If you didn’t break the problem down enough, try going back to the second step and being as meticulous as possible.  Write out each and every single step.  I know it is a pain, but do it, believe me it will be worth the effort.

If you don’t know your programming language well enough to do the translation, you may need to brush up here on some basic constructs.  Any language you expect to be able to solve algorithm type problems in, you should know how to do the following things:

  • Create a list
  • Sort a list or array
  • Create a map or dictionary
  • Loop through a list, or dictionary
  • Parse strings
  • Convert from string to int, int to string, etc

If you don’t know how to do all of these things.  Stop what you are doing now and learn them. It’s not a very long list, and the benefits will be profound.

Optimize the real code

Sometimes this step isn’t necessary, but it’s worth taking a look at your code and figuring out if you can cut out a few lines or do something simpler.

This is also a good place to make sure all your variables are named with long meaningful names.  I cannot stress enough how important having good names for your variables and methods is for helping the person evaluating your code to understand what you were trying to do.  This is especially important when you make a mistake!

I won’t give an optimization for our trivial example of a string reversal, but a word of advice here is not to get too tricky.  Just try to mainly simplify your code and get rid of duplication.

A few final tips

If you follow this template for solving algorithm type problem, you should do very well in programming interviews, but the key to doing so is having confidence in this process.

The only way you are going to have confidence in this process is to practice it.  It takes a good amount of faith to believe that spending 70% of your 30 minutes to solve a problem just thinking about the problem and not writing any code is the right approach, so make sure you have that faith when you need it.

I’ve talked about using TopCoder to become a better programmer before, and I still recommend it.  Codility.com is another great site I have recently been introduced to.

There is one important step I did not include in the outline above, because I didn’t want to make the process any more complicated than it needed to be.

Many times you will find that a problem itself involves multiple large steps or is very complicated.  In those instances, you will want to try and find a way to cut the problem directly in half and then following the process above for each half.

This method of tackling a problem is called “divide and conquer” and is quite effective.  A good way to know where to break a problem in half is to think about what part of the problem if already given to you would make solving the rest easy.

The programming interview is merely one battle in a larger war: marketing yourself. For the full lowdown, take a look at my course: How to Market Yourself as a Software Developer .

IMAGES

  1. Six Steps to Solving a Programming Problem Infographic

    how do programmers approach problem solving and coding

  2. Problem Solving

    how do programmers approach problem solving and coding

  3. 6 Ways to Improve Your Programming Problem Solving

    how do programmers approach problem solving and coding

  4. How To Solve A Programming Problem : A Seven Step Approach

    how do programmers approach problem solving and coding

  5. How to Solve Coding Problems with a Simple Four Step Method

    how do programmers approach problem solving and coding

  6. Problem Solving Techniques

    how do programmers approach problem solving and coding

VIDEO

  1. programming idea

  2. A Simple Technique to Solve Coding Problems

  3. 💡programmers think like a problem solver so is the algorithm and flowchart #coding #algorithm

  4. The Mindset of Successful Programmers

  5. Coding Ninja Questions Left Rotate an Array by One #shorts #coding #codingninja

  6. Solve TwoSum in Python

COMMENTS

  1. How to Solve Coding Problems with a Simple Four Step Method

    In this post, we've gone over the four-step problem-solving strategy for solving coding problems. Let's review them here: Step 1: understand the problem. Step 2: create a step-by-step plan for how you'll solve it. Step 3: carry out the plan and write the actual code.

  2. How To Approach A Coding Problem

    These steps you need to follow while solving a problem: - Understand the question, read it 2-3 times. - Take an estimate of the required complexity. - find, edge cases based on the constraints. - find a brute-force solution. ensure it will pass. - Optimize code, ensure, and repeat this step. - Dry-run your solution (pen& paper) on ...

  3. How to Think like a Programmer

    Then write the code to solve that small problem. Slowly but surely, introduce complexity to solve the larger problem you were presented with at the beginning. 5. Practice, don't memorize. Memorizing code is tough, and you don't need to go down that road to think like a programmer. Instead, focus on the fundamentals.

  4. How to Develop Problem Solving Skills in Programming

    The way to approach problems is the key to improving the skills. To find a solution, a positive mindset helps to solve problems quickly. If you think something is impossible, then it is hard to achieve. When you feel free and focus with a positive attitude, even complex problems will have a perfect solution.

  5. A Guide to Problem-Solving for Software Developers with Examples

    It's even better if the members of the team are used to swim in uncertainty, and take it as a challenge more than a chore. The process described above is just an example; in practice it's often more chaotic. For example, even when a decision is made, your brain might still continue to process the problem passively.

  6. The Beginner Programmer's guide to Problem Solving [With Example]

    Step 3: Connect the dots (Integration) You have solved individual problems. Now it is time to connect the dots by connecting the individual solution. Identify those steps which will make the solution or the program complete. Typically in programming, the dots are connected by passing data that is stored in variables.

  7. Mastering Programming Challenges: Five In-Depth Problem-Solving

    Identify the main steps or components needed to solve the problem. Tackle each subproblem one at a time, focusing on solving each part independently. Once you have working solutions for the subproblems, combine them to solve the larger problem. This approach not only simplifies complex problems but also allows you to approach each part with a ...

  8. The 5 Pillars of Complex Problem Solving with Code

    2. After spending hundreds of hours helping people take their first steps with code, I developed a five part model for problem solving. In fact, it's even easier than that, as it really breaks down to three core skills, and two processes. In this piece I'll explain each of them and how they interreact.

  9. UNIT 1: How to Think Like an Engineer.

    Computational Thinking is the thought processes involved in understanding a problem and expressing its solution in a way that a computer can effectively carry out. Computational thinking involves solving problems, designing systems, and understanding human behavior (e.g. what the user needs or wants) - thinking like an engineer. Computational ...

  10. What exactly is a programming paradigm?

    The functional programming paradigm has its roots in mathematics and it is language independent. The key principle of this paradigm is the execution of a series of mathematical functions. You compose your program of short functions. All code is within a function. All variables are scoped to the function.

  11. How to solve coding problems step by step

    The first and most important step in solving any coding problem is to understand the problem statement. Read the instructions carefully and make sure you fully comprehend the requirements. Break down the problem into smaller, manageable tasks and try to visualize the expected input and output. Choose the Right Data Structure and Algorithm.

  12. 10 Steps to Solving a Programming Problem

    The goal is to take all the even numbers and return them in an array. If there are no even numbers, return an empty array. 2. Work through the problem manually with at least three sets of sample data. Take out a piece of paper and work through the problem manually.

  13. How to solve coding problems. Practical problem solving strategies

    E very single line of code ever written was ultimately made with one purpose in mind: to solve problems. No matter what you do, you are solving problems on several scales at once. A small one-liner solves a problem which makes a function work. The function is needed for a data processing pipeline.

  14. Hands-on Tutorial: How To Improve Your Problem-Solving Skills As A

    Programming is ultimately problem-solving. We only apply the programming language to express how we've thought about a problem and the approach we're using to solve it. The worst thing you could do is to start chipping away at the problem once it's presented. This is where most newbie programmers get stuck and give up.

  15. How to Solve Coding Challenges: A Comprehensive Guide

    1. Understand the Problem. The first and most crucial step in solving any coding challenge is thoroughly understanding the problem statement. To do this: Read Carefully: Begin by reading the ...

  16. 7 Tips on How to Approach and Solve Coding Problems Successfully

    Create a flow chart illustrating the problem. Break it into subproblems or smaller sections. Solve each section by creating independent functions. Arrange the functions in the order you need, thereby merging them all for the final solution. In case of errors, you can debug the code and search for an alternate approach.

  17. 7-Step Approach to Solve Any Coding Problem (Important for Interviews)

    For this problem, your pseudo code might go something like this-. // Create a sum variable. Add the first input to the second input using the addition operator. // Store values of both inputs into the sum variable. // Return as output the sum variable. This would be the step-by-step plan to reach the solution.

  18. How to Solve Programming Problems

    A simple set of steps. I am going to give you a simple set of steps to follow which you can use for any algorithm type programming problem. Read the problem completely twice. Solve the problem manually with 3 sets of sample data. Optimize the manual steps. Write the manual steps as comments or pseudo-code. Replace the comments or pseudo-code ...

  19. PDF Problem Solving Basics and Computer Programming

    We can do this in four steps. 1. Identify all of the nouns in the sentence. Given the 3 dimensions of a box (length, width, and height), calculate the volume. The nouns in the problem specification identify descriptions of information that you will need to either identify or keep track of.

  20. Enhancing problem‐solving skills of novice programmers in an

    1 INTRODUCTION. Problem-solving skills play an important role in learning to code for novice programmers [].These skills help students to devise the solution to the given problem statement [].Moreover, it is important for students to understand the requirements of the given problem statement (input, output, and process) to start working on its solution.

  21. How to Solve any Programming Problem

    Always Plan a solution first. Once you have the details and understand the problem it is time to plan a solution. This is the part where you analyze the constraints and the rules, strategize a ...