problem solving programming questions

100+ Coding Interview Questions for Programmers and Software Engineers in 2024

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

codeburst

Coding Interviews are such an important thing in a programmer’s life that he just can’t get away with that. It’s the first hurdle they need to cross to get the software developer job they wish throughout their school and college days.

To make the matter worse, you will find that so many people on the internet telling that coding interview is flawed, the hiring process for programmers sucks, and so on but you don’t need to pay attention to them, not at least at the start of your career.

They may be right but they are inside the train which you are trying to get into. No matter, how much they criticize the coding interviews and programmers hiring process, many of them have gone through the same route to where they are.

We all know that Coding Interview System is not perfect and many are trying to change it but until it's changed, you got to follow its rules to get into the System. This is something for experience developers to deal with, as a junior developer your priority should be to clear the coding interview and get the job you want.

As an author of a Java blog and a Medium publication , I receive a lot of queries related to coding problems and how to deal with them and that’s why I keep writing articles like this which have helped a lot of programmers directly and in-directly in their career.

In this article, I am going to share with you the top 100 coding interview problems from programming job interviews which every programmer should know.

What to prepare for Coding Interviews?

Now that, I have cleared the confusion that Coding interviews is important and you should not distract, let’s get into real work. The big question is what to prepare for Coding interviews?

Well, the most important thing to prepare is Data Structure-based coding problems like array-based coding problems, string problems, linked list problems, binary tree problems, etc.

Apart from data structure-based questions, most of the programming job interviews also ask algorithm, design, bit manipulation, and general logic-based questions, which I’ll describe in this section.

It’s important that you practice these concepts because sometimes they become tricky to solve in the actual interview. Having practiced them before not only makes you familiar with them but also gives you more confidence in explaining the solution to the interviewer.

One of the main problems with coding problems is that there are hundreds and thousands of coding problems on interviews, there are even sites like LeetCode , HackerRank , Codewars , Topcoder , freeCodeCamp , HackerEarth which train programmers for coding interviews with lots of tough questions, which sometimes just overwhelms a beginner looking for a job.

I believe in simplicity and the 10% of effort which produce 90% of results and that’s why I have collected top 100 coding problems which are not too tough and also frequently asked on real interviews.

Solving these problems not only gives you confidence but also helps you to recognize some of the most common algorithmic patterns which will also help you to solve some unseen problems in real interviews.

Best Resources for Coding Interviews

The selection of good resources is very important for success in your coding interviews. If you chose the wrong resource then more than money, you will lose the valuable time you need for preparation, hence spending some time researching for a good resource.

If you need recommendations, the following are some of my the tried and tested resources to learn Data Structure and Algorithms in-depth for coding interviews:

  • Data Structures and Algorithms: Deep Dive Using Java for Java developers. Learn about Arrays, Linked Lists, Trees, Hashtables, Stacks, Queues, Heaps, Sort algorithms, and Search algorithms

Data Structures and Algorithms: Deep Dive Using Java

So you've worked with the basics of data structures and algorithms in java (or another oo programming language) but….

  • Algorithms and Data Structures in Python for those who love Python A guide to implementing the most up to date algorithms from scratch: arrays, linked lists, graph algorithms, and sorting

Algorithms and Data Structures in Python

This course is about data structures and algorithms. we are going to implement the problems in python. i highly….

  • JavaScript Algorithms and Data Structures Masterclass by Colt_Steele for JavaScript programmers. The Missing Computer Science and Coding Interview Bootcamp. Learn everything you need to ace difficult coding interviews.

JavaScript Algorithms and Data Structures Masterclass

This course crams months of computer science and interview prep material into 20 hours of video. the content is based….

  • Mastering Data Structures & Algorithms using C and C++ for those who are good at C/C++
  • Data Structures in Java: An Interview Refresher by The Educative Team to refresh important Data Structure and algorithms concepts in Java. This course contains a detailed review of all the common data structures and provides implementation-level details in Java to allow readers to become well equipped.
  • Grokking the Coding Interview: Patterns for Coding Questions by Fahim ul Haq and The Educative Team This is like the meta course for coding interviews, which will not teach you how to solve a coding problem but, instead, teach you how to solve a particular type of coding problem using patterns. Master these 15 underlying patterns to interview questions, and you’ll be able to tackle anything you face on the interview

Grokking the Coding Interview: Patterns for Coding Questions

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

www.educative.io

System Design is another topic which is quite important for coding interviews and when it comes to System design , there are not many places where you can learn System design concepts and architecture in depth, but ByteByteGo is exceptional.

ByteByteGo | Ace Your Next System Design Interview

Everything you need to take your system design skill to the next level.

bytebytego.com

It’s one of those sites where I have learned a lot. They explain many key System design concept like Microservices , load balancing, caching, Algorithms like CAP theorem and how to design a particular system with easily digestible diagram. It’s created by Alex Xu, author of System Design Interview — An insider’s guide , one of the best System Design book , and I highly recommend this to everyone preparing for coding interviews.

System Design Interview - An insider's guide

Buy system design interview - an insider's guide on amazon.com ✓ free shipping on qualified orders.

www.amazon.com

And, if you prefer books, there is no better than the Cracking The Coding Interview , by Gayle Laakmann McDowell which presents 189+ Programming questions and solutions. A good book to prepare for programming job interviews in a short time. Btw, I will also earn some money if you buy any of these resources mentioned here.

5 Best Tips to Crack Coding Interviews in 2023

Here are a few of my practical tips to crack your next coding interview. These are hard-earned and I learned from my own mistakes and experience.

  • There is no better way to do well in Coding interviews than practicing as many coding problems as possible. This will not only train your mind to recognize algorithmic patterns in problems but also give you the much-needed confidence to solve problems you have never seen before.
  • My second tips are to learn about as many data structure and algorithms as possible. This is an extension of the previous tip but it also involves reading and not just practicing. For example, If you know about the hash table you can also many array and counter-based problems easily. The same is true for trees and graphs.
  • Choosing the right data structure is a very important part of software development and coding interview and unless and until you know them, you won’t be able to choose.
  • Time yourself — candidates who solve interview problems within the time limit and quickly are more likely to do well in the interview so you should also time yourself.
  • Think of edge cases and run your code through them. Some good edge cases might be the empty input, some weird input, or some really large input to test the boundary conditions and limits.
  • After solving the problem, try explaining it to a friend or colleague how is also interested in coding problems. This will tell you whether you have really understood the problem or not. If you can explain easily means you understood . Also, the discussion makes your mind work and you could come up with an alternative solution and be able to find some flaws in your existing algorithms.
  • Another useful tip to excel in Coding interviews is to appear in the coding interview and lots of them. You will find yourself getting better after every interview and this also helps you to get multiple offers which further allows you to better negotiate and get those extra 30K to 50K which you generally leave on a table if you just have one offer in hand.
  • Btw, If you are ready for Coding Interview then you can also take TripleByte’s quiz and go directly to the final round of interviews with top tech companies like Coursera , Adobe Acrobat , Dropbox , Grammarly , Uber , Quora , Evernote , Twitch , and many more. I didn’t know about Triplebyte before, but they are providing a great service to job seekers. A big thanks to them.

Triplebyte: Software Engineer Job Search

Take a quiz. get offers from multiple top tech companies at once..

triplebyte.com

Top 100 Coding Problems from Programming Job interviews

Without wasting any more of your time, here is my list of 100 frequently asked coding problems from programming job interviews. In order to get most of this list, I suggest actually solving the problem.

Do it yourself, no matter whether you are stuck because that’s the only way to learn. After solving a couple of problems you will gain confidence.

I also suggest you look at the solution when you are stuck or after you have solved the problem, this way you learn to compare different solutions and how to approach a problem from a different angle.

  • How is a bubble sort algorithm implemented? ( solution )
  • How is a merge sort algorithm implemented? ( solution )
  • How do you count the occurrence of a given character in a string? ( solution )
  • How do you print the first non-repeated character from a string? ( solution )
  • How do you convert a given String into int like the atoi() ? ( solution )
  • How do you implement a bucket sort algorithm? ( solution )
  • How do you implement a counting sort algorithm? ( solution )
  • How do you remove duplicates from an array in place? ( solution )
  • How do you reverse an array in place in Java? ( solution )
  • How are duplicates removed from an array without using any library? ( solution )
  • How is a radix sort algorithm implemented? ( solution )
  • How do you swap two numbers without using the third variable? ( solution )
  • How do you check if two rectangles overlap with each other? ( solution )
  • How do you design a vending machine? ( solution )
  • How do you find the missing number in a given integer array of 1 to 100? ( solution )
  • How do you find the duplicate number on a given integer array? ( solution )
  • How do you find duplicate numbers in an array if it contains multiple duplicates? ( solution )
  • Difference between a stable and unstable sorting algorithm? ( answer )
  • How is an iterative quicksort algorithm implemented? ( solution )
  • How do you find the largest and smallest number in an unsorted integer array? ( solution )
  • How do you reverse a linked list in place? (solution)
  • How to add an element at the middle of the linked list? (solution)
  • How do you sort a linked list in Java? ( solution )
  • How do you find all pairs of an integer array whose sum is equal to a given number? ( solution )
  • How do you implement an insertion sort algorithm? ( solution )
  • How are duplicates removed from a given array in Java? ( solution )
  • how to remove the duplicate character from String? ( solution )
  • How to find the maximum occurring character in a given String? ( solution )
  • How is an integer array sorted in place using the quicksort algorithm? ( solution )
  • How do you reverse a given string in place? ( solution )
  • How do you print duplicate characters from a string? ( solution )
  • How do you check if two strings are anagrams of each other? ( solution )
  • How do you find all the permutations of a string? ( solution )
  • How can a given string be reversed using recursion? ( solution )
  • How do you check if a given string is a palindrome? ( solution )
  • How do you find the length of the longest substring without repeating characters? (solution)
  • Given string str, How do you find the longest palindromic substring in str? (solution)
  • How do you check if a string contains only digits? ( solution )
  • How to remove Nth Node from the end of a linked list? ( solution )
  • How to merge two sorted linked lists? (solution)
  • How to convert a sorted list to a binary search tree? ( solution )
  • How do you find duplicate characters in a given string? ( solution )
  • How do you count the number of vowels and consonants in a given string? ( solution )
  • How do you reverse words in a given sentence without using any library method? ( solution )
  • How do you check if two strings are a rotation of each other? ( solution )
  • How to convert a byte array to String? ( solution )
  • How do you remove a given character from String? ( solution )
  • How do you find the middle element of a singly linked list in one pass? ( solution )
  • How do you check if a given linked list contains a cycle? How do you find the starting node of the cycle? ( solution )
  • How do you reverse a linked list? ( solution )
  • How do you reverse a singly linked list without recursion? ( solution )
  • How are duplicate nodes removed in an unsorted linked list? ( solution )
  • How do you find the length of a singly linked list? ( solution )
  • How do you find the third node from the end in a singly linked list? ( solution )
  • How do you find the sum of two linked lists using Stack? ( solution )
  • What is the difference between array and linked list? ( answer )
  • How to remove duplicates from a sorted linked list? ( solution )
  • How to find the node at which the intersection of two singly linked lists begins. ( solution )
  • Given a linked list and a value x , partition it such that all nodes less than x come before nodes greater than or equal to x . ( solution )
  • How to check if a given linked list is a palindrome? (solution)
  • How to remove all elements from a linked list of integers which matches with given value? (solution)
  • How is a binary search tree implemented? ( solution )
  • How do you perform preorder traversal in a given binary tree? ( solution )
  • How do you traverse a given binary tree in preorder without recursion? ( solution )
  • How do you perform an inorder traversal in a given binary tree? ( solution )
  • How do you print all nodes of a given binary tree using inorder traversal without recursion? ( solution )
  • How do you implement a postorder traversal algorithm? ( solution )
  • How do you traverse a binary tree in postorder traversal without recursion? ( solution )
  • How are all leaves of a binary search tree printed? ( solution )
  • How do you count a number of leaf nodes in a given binary tree? ( solution )
  • How do you perform a binary search in a given array? ( solution )
  • How to Swap two numbers without using the third variable? ( solution )
  • How to check if two rectangles overlap with each other? ( solution )
  • How to design a Vending Machine? ( solution )
  • How to implement an LRU Cache in your favorite programming language? ( solution )
  • How to check if a given number is a Palindrome? ( solution )
  • How to check if a given number is an Armstrong number? ( solution )
  • How to find all prime factors of a given number? ( solution )
  • How to check if a given number is positive or negative in Java? ( solution )
  • How to find the largest prime factor of a given integral number? ( solution )
  • How to print all prime numbers up to a given number? ( solution )
  • How to print Floyd’s triangle? ( solution )
  • How to print Pascal’s triangle? ( solution )
  • How to calculate the square root of a given number? ( solution )
  • How to check if the given number is a prime number? ( solution )
  • How to add two numbers without using the plus operator in Java? ( solution )
  • How to check if a given number is even/odd without using the Arithmetic operator? ( solution )
  • How to print a given Pyramid structure? ( solution )
  • How to find the highest repeating world from a given file in Java? ( solution )
  • How to reverse a given Integer in Java? ( solution )
  • How to convert a decimal number to binary in Java? ( solution )
  • How to check if a given year is a leap year in Java? ( solution )
  • Can you implement a Binary search Algorithm without recursion? ( solution )
  • What is Depth First Search Algorithm for a binary tree? (solution)
  • What is the difference between Comparison and Non-Comparison Sorting Algorithms? ( answer )
  • How do implement Sieve of Eratosthenes Algorithms for Prime Number? ( solution )

These many questions should be enough but If you need more such coding questions you can take help from books like Cracking The Code Interview , by Gayle Laakmann McDowell which presents 189+ Programming questions and solutions. A good book to prepare for programming job interviews in a short time.

Now You’re Ready for the Coding Interview

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

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

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

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

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

Further Learning Data Structures and Algorithms: Deep Dive Using Java 10 Books to Prepare Technical Programming/Coding Job Interviews 10 Algorithm Books Every Programmer Should Read Top 5 Data Structure and Algorithm Books for Java Developers From 0 to 1: Data Structures & Algorithms in Java Data Structure and Algorithms Analysis — Job Interview 20+ String based coding problems from interviews 20+ linked list problems from interviews 20+ basic algorithms based problems from interviews ByteByteGo for System Design and Architecture

And, if you like to watch videos, here are videos where you will data structure and algorithms courses and tutorials:

and here are free DSA tutorials

Closing Notes

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

By the way, the more questions you solve in practice, the better your preparation will be.

So, if you think 100 coding problems are not enough and you need more, then check out these additional 50 programming questions for telephone interviews and these books and courses for more thorough preparation.

All the best for your coding interview.

Other Articles you may like:

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

Algorithms and data structure are two of the most fundamentals and essential topics from computer science, which is…, 10 best books for data structure and algorithms for beginners in java, c/c++, and python, algorithms are language agnostic, and any programmer worth their salt should be able to convert them to code in their…, my favorite free courses to learn data structures and algorithms in depth, by javinpaul data structures and algorithms are some of the most essential topics for programmers, both to get a job….

www.freecodecamp.org

codeburst

Written by javinpaul

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

More from javinpaul and codeburst

The 2024 Software Architect or Solution Architect RoadMap

Javarevisited

The 2024 Software Architect or Solution Architect RoadMap

An illustrated guide to becoming a software architect in 2024 with links to relevant courses.

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

The 2024 AI (Artificial Intelligence) Developer RoadMap

The 2024 AI (Artificial Intelligence) Developer RoadMap

An illustrated guide to becoming a ai engineer in 2024 with links to relevant courses, recommended from medium.

Mastering Design Patterns in Java

Dharshi Balasubramaniyam

Mastering Design Patterns in Java

Figure 1: design patterns.

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.

problem solving programming questions

General Coding Knowledge

problem solving programming questions

Coding & Development

problem solving programming questions

Stories to Help You Grow as a Software Developer

problem solving programming questions

Predictive Modeling w/ Python

Practical Tips for Job Searching

Practical Tips for Job Searching

In the ever-changing landscape of the job market, finding a new job can seem like a challenging expedition. i’ve had the privilege of….

I Solved 300+ Leetcode problems , Here is what I learnt.

I Solved 300+ Leetcode problems , Here is what I learnt.

Cracking the Machine Learning Interview: A Comprehensive Guide

Ramy Hussein

Cracking the Machine Learning Interview: A Comprehensive Guide

Get ready to ace the machine learning interview process with this handy guide i’ll walk you through each round, from testing your general….

Top 60 Spring-Framework Interview Questions for Java Developers 2024(Contain All the Questions from…

Ajay Rathod

Top 60 Spring-Framework Interview Questions for Java Developers 2024(Contain All the Questions from…

Hey there if you’re a java developer, mastering the spring framework is crucial for backend development. it serves as the foundation for….

Text to speech

Top 72 Swift Interview Questions

40 Coding Challenges (SOLVED with CODE) To Kill Your Next Coding Interview

Top 12 Bit Manipulation Interview Questions

You may hate code challenges and coding interviews but reality is a lot of companies from Google to Amazon do care that you understand the difference between O(n log n) and O(n²) , that you do understand when different data structures are appropriate, and that you can leverage these (very basic) skills to solve simple problems. Follow along and check 40 most common Coding Challenges and Questions that solved with code on Java, C#, Python and JS to crack and close your next coding interview.

Q1 :   Convert a Single Linked List to a Double Linked List

A doubly linked list is simply a linked list where every element has both next and prev mebers, pointing at the elements before and after it, not just the one after it in a single linked list.

so to convert your list to a doubly linked list, just change your node to be:

and when iterating the list, on each new node add a reference to the previous node.

Q2 :   Convert a Singly Linked List to Circular Linked List

To convert a singly linked list to a circular linked list, we will set the next pointer of the tail node to the head pointer.

  • Create a copy of the head pointer, let's say temp .
  • Using a loop, traverse linked list till tail node (last node) using temp pointer.
  • Now set the next pointer of the tail node to head node. temp->next = head

Q3 :   Detect if a List is Cyclic using Hash Table

To detect if a list is cyclic, we can check whether a node had been visited before. A natural way is to use a hash table.

We go through each node one by one and record each node's reference (or memory address) in a hash table. If the current node is null , we have reached the end of the list and it must not be cyclic. If current node’s reference is in the hash table, then return true.

Space: O(n)

  • Time complexity : O ( n ) . We visit each of the n elements in the list at most once. Adding a node to the hash table costs only O ( 1 ) time.
  • Space complexity: O ( n ) . The space depends on the number of elements added to the hash table, which contains at most n elements.

Q4 :   Implement Stack using Two Queues (with efficient push )

Given two queues with their standard operations ( enqueue , dequeue , isempty , size ), implement a stack with its standard operations ( pop , push , isempty , size ). The stack should be efficient when pushing an item.

Given we have queue1 and queue2 :

push - O(1) :

  • enqueue in queue1

pop - O(n) :

  • while size of queue1 is bigger than 1, pipe (dequeue + enqueue) dequeued items from queue1 into queue2
  • dequeue and return the last item of queue1 , then switch the names of queue1 and queue2

Space: O(1)

If queue is implemented as linked list the enqueue operation has O(1) time complexity.

Q5 :   Implement a Queue using two Stacks

Suppose we have two stacks and no other temporary variable. Is to possible to "construct" a queue data structure using only the two stacks?

Keep two stacks, let's call them inbox and outbox .

  • Push the new element onto inbox
  • If outbox is empty, refill it by popping each element from inbox and pushing it onto outbox
  • Pop and return the top element from outbox

In the worst case scenario when outbox stack is empty, the algorithm pops n elements from inbox stack and pushes n elements to outbox, where n is the queue size. This gives 2*n operations, which is O(n) . But when outbox stack is not empty the algorithm has O(1) time complexity that gives amortised O(1) .

Q6 :   Insert item into the Heap. Explain your actions.

Suppose I have a Heap Like the following:

Now, I want to insert another item 55 into this Heap. How to do this?

A binary heap is defined as a binary tree with two additional constraints:

  • Shape property : a binary heap is a complete binary tree; that is, all levels of the tree, except possibly the last one (deepest) are fully filled, and, if the last level of the tree is not complete, the nodes of that level are filled from left to right.
  • Heap property : the key stored in each node is either greater than or equal to (≥) or less than or equal to (≤) the keys in the node's children, according to some total order.

We start adding child from the most left node and if the parent is lower than the newly added child than we replace them. And like so will go on until the child got the parent having value greater than it.

Your initial tree is:

Now adding 55 according to the rule on most left side:

But you see 22 is lower than 55 so replaced it:

Now 55 has become the child of 50 which is still lower than 55 so replace them too:

Now it cant be sorted more because 77 is greater than 55.

Q7 :   Return the N-th value of the Fibonacci sequence Recursively

Recursive solution looks pretty simple (see code).

Let’s look at the diagram that will help you understand what’s going on here with the rest of our code. Function fib is called with argument 5:

Basically our fib function will continue to recursively call itself creating more and more branches of the tree until it hits the base case, from which it will start summing up each branch’s return values bottom up, until it finally sums them all up and returns an integer equal to 5.

Time: O(2^n)

In case of recursion the solution take exponential time, that can be explained by the fact that the size of the tree exponentially grows when n increases. So for every additional element in the Fibonacci sequence we get an increase in function calls. Big O in this case is equal to O ( 2 n ) . Exponential Time complexity denotes an algorithm whose growth doubles with each addition to the input data set.

Q8 :   Return the N-th value of the Fibonacci sequence. Solve in O(n) time

The easiest solution that comes to mind here is iteration:

And output:

Notice that two first numbers can not really be effectively generated by a for loop, because our loop will involve adding two numbers together, so instead of creating an empty array we assign our arr variable to [0, 1] that we know for a fact will always be there. After that we create a loop that starts iterating from i = 2 and adds numbers to the array until the length of the array is equal to n + 1 . Finally, we return the number at n index of array.

An algorithm in our iterative solution takes linear time to complete the task. Basically we iterate through the loop n-2 times, so Big O (notation used to describe our worst case scenario) would be simply equal to O (n) in this case. The space complexity is O(n) .

Q9 :   Reverse a String using Stack

The followings are the steps to reversing a String using Stack:

  • String to char[] .
  • Create a Stack .
  • Push all characters, one by one.
  • Then Pop all characters, one by one and put into the char[] .
  • Finally, convert to the String .

Q10 :   What is complexity of push and pop for a Stack implemented using a LinkedList?

O ( 1 ) . Note, you don't have to insert at the end of the list. If you insert at the front of a (singly-linked) list, they are both O(1) .

Stack contains 1,2,3:

Q11 :   What would the number 22 look like as a Byte?

A byte is made up of 8 bits and the highest value of a byte is 255, which would mean every bit is set.

Lets take it right to left and add up all those values together:

128 0 + 64 0 + 32 0 + 16 1 + 8 0 + 4 1 + 2 1 + 1 0 = 22

Q12 :   Check if parentheses are balanced using Stack

One of the most important applications of stacks is to check if the parentheses are balanced in a given expression. The compiler generates an error if the parentheses are not matched.

Here are some of the balanced and unbalanced expressions:

  • Declare a character stack which will hold an array of all the opening parenthesis.
  • Now traverse the expression string exp.
  • If the current character is a starting bracket ( ( or { or [ ) then push it to stack.
  • If the current character is a closing bracket ( ) or } or ] ) then pop from stack and if the popped character is the matching starting bracket then fine else parenthesis are not balanced.
  • After complete traversal, if there is some starting bracket left in stack then “not balanced”
  • We are traversing through each character of string, Time complexity O ( n ) .
  • We are storing the opposite parentheses characters in the stack, in the worst case there can be all the opposite characters in the string, Space complexity O ( n ) .

Q13 :   Explain how Heap Sort works

Heapsort is a comparison-based sorting algorithm. Heapsort can be thought of as an improved selection sort : like that algorithm, it divides its input into a sorted and an unsorted region, and it iteratively shrinks the unsorted region by extracting the largest element and moving that to the sorted region. The improvement consists of the use of a heap data structure rather than a linear-time search to find the maximum.

A heap is a complete binary tree (every level filled as much as possible beginning at the left side of the tree) that follows this condition: the value of a parent element is always greater than the values of its left and right child elements. So, by taking advantage of this property, we can pop off the max of the heap repeatedly and establish a sorted array .

In an array representation of a heap binary tree, this essentially means that for a parent element with an index of i , its value must be greater than its left child [2i+1] and right child [2i+2] (if it has one).

The HeapSort steps are:

  • Create a max heap from the unsorted list
  • Swap the max element, located at the root, with the last element
  • Re- heapify or rebalance the array again to establish the max heap order. The new root is likely not in its correct place.
  • Repeat Steps 2–3 until complete (when the list size is 1)

Visualisation :

Complexity:

Time: O(n log n)

  • Best : O ( n log n )
  • Average : O ( n log n )
  • Worst : O ( n log n )

Q14 :   Find all the Permutations of a String

A permutation , also called an “arrangement number” or “order,” is a rearrangement of the elements of an ordered list S into a one-to-one correspondence with S itself (or in simple english: permutation is each of several possible ways in which a set or number of things can be ordered or arranged). A string of length n has n! permutation:

To print all permutations of a string use backtracking implemented via recursion :

  • Try each of the letters in turn as the first letter and then find all the permutations of the remaining letters using a recursive call.
  • The base case is when the input is an empty string the only permutation is the empty string.
  • In other words, you simply traverse the tree, and when you reach the leaf you print the permutation. Then you backtrack one level up, and try another option. Moving one level up the tree is what we call the backtracking in this case.

Time: O(n!)

Space: O(n!)

For any given string of length n there are n! possible permutations, and we need to print all of them so Time complexity is O(n * n!) . The function will be called recursively and will be stored in call stack for all n! permutations, so Space complexity is O(n!) .

Q15 :   Floyd's Cycle Detect Algorithm: Explain how to find a starting node of a Cycle in a Linked List?

This is Floyd's algorithm for cycle detection . Once you've found a node that's part of a cycle, how does one find the start of the cycle?

  • In the first part of Floyd's algorithm, the hare moves two steps for every step of the tortoise. If the tortoise and hare ever meet, there is a cycle, and the meeting point is part of the cycle, but not necessarily the first node in the cycle.
  • Once tortoise and hare meet, let's put tortoise back to the beginning of the list and keep hare where they met (which is k steps away from the cycle beginning). The hypothesis (see math explanation) is that if we let them move at the same speed (1 step for both), the first time they ever meet again will be the cycle beginning .

Another solution to mention is Hash Map :

  • Traverse the nodes list.
  • For each node encountered, add it to the identity hash map
  • If the node already existed in the identity map then the list has a circular link and the node which was prior to this conflict is known (either check before moving or keep the "last node")

Q16 :   Floyd's Cycle Detect Algorithm: How to detect a Cycle (or Loop) in a Linked List?

You can make use of Floyd's cycle-finding algorithm , also known as tortoise and hare algorithm . The idea is to have two references to the list and move them at different speeds . Move one forward by 1 node and the other by 2 nodes.

  • If the linked list has a loop they will definitely meet.
  • Else either of the two references(or their next ) will become null .

We only use two nodes (slow and fast) so the space complexity is O ( 1 ) .

Q17 :   Floyd's Cycle Detect Algorithm: Remove Cycle (Loop) from a Linked List

Floyd's cycle detect algorithm, also called the tortoise and hare algorithm as it involves using two pointers/references that move at different speeds, is one way of detecting the cycle. If there is a cycle, the two pointers (say slow and fast ) will end up pointing to the same element after a finite number of steps. Interestingly, it can be proved that the element at which they meet will be the same distance to the start of the loop (continuing to traverse the list in the same, forward direction) as the start of the loop is to the head of the list . That is, if the linear part of the list has k elements, the two pointers will meet inside the loop of length m at a point m-k from the start of the loop or k elements to the 'end' of the loop (of course, it's a loop so it has no 'end' - it's just the 'start' once again). And that gives us a way to find the start of the loop:

Once a cycle has been detected, let fast remain pointing to the element where the loop for the step above terminated but reset slow so that it's pointing back to the head of the list. Now, move each pointer one element at a time. Since fast began inside the loop, it will continue looping. After k steps (equal to the distance of the start of the loop from the head of the list), slow and fast will meet again. This will give you a reference to the start of the loop.

It is now easy to set slow (or fast ) to point to the element starting the loop and traverse the loop until slow ends up pointing back to the starting element. At this point slow is referencing the 'last' element list and it's next pointer can be set to null .

Q18 :   Get the N-th Fibonacci number with O(n) time and O(1) space complexity

This solution is in linear O(n) time complexity, and constant O(1) space complexity. The number of loops it takes to calculate the nth fib number will still increase at a linear rate as n increases, but we are overriding the previous numbers in the sequence as we build it out, making the space complexity constant for any input n. It's also called Iterative Top-Down Approach .

Q19 :   How to check if String is a Palindrome?

A palindrome is a word, phrase, number or other sequence of units that can be read the same way in either direction . You can check if a string is a palindrome by comparing it to the reverse of itself either using simple loop or recursion .

The time complexity is O(n/2) that is still O ( n ) . We doing n comparisons, where n = s.length() . Each comparison takes O ( 1 ) time, as it is a single character comparison. You can cut the complexity of the function in half by stopping at i == (s.length() / 2)+1 . It is not relevant in Big O terms, but it is still a pretty decent gain. Loop approach has constant space complexity O ( 1 ) as we not allocating any new memory. Reverse string approach needs O ( n ) additional memory to create a reversed copy of a string. Recursion approach has O ( n ) space complexity due call stack.

Recursion :

You may want to solve the problem by inverting the original string in a whole but note the space complexity will be worst than for the loop solution ( O(n) instead of O(1) ):

Q20 :   How to check if two Strings (words) are Anagrams ?

Explain what is space complexity of that solution?

Two words are anagrams of each other if they contain the same number of characters and the same characters. There are two solutions to mention:

  • You should only need to sort the characters in lexicographic order, and determine if all the characters in one string are equal to and in the same order as all of the characters in the other string. If you sort either array, the solution becomes O(n log n) .
  • Hashmap approach where key - letter and value - frequency of letter,
  • for first string populate the hashmap O(n)
  • for second string decrement count and remove element from hashmap O(n)
  • if hashmap is empty, the string is anagram otherwise not.

The major space cost in your code is the hashmap which may contain a frequency counter for each lower case letter from a to z . So in this case, the space complexity is supposed to be constant O(26) .

To make it more general, the space complexity of this problem is related to the size of alphabet for your input string. If the input string only contains ASCII characters, then for the worst case you will have O(256) as your space cost. If the alphabet grows to the UNICODE set, then the space complexity will be much worse in the worst scenario.

So in general its O(size of alphabet) .

Q21 :   How to find Nth element from the end of a singly Linked List?

Use lockstep solution. The key to this algorithm is to set two pointers p1 and p2 apart by n-1 nodes initially so we want p2 to point to the (n-1)th node from the start of the list then we move p2 till it reaches the last node of the list. Once p2 reaches end of the list p1 will be pointing to the Nth node from the end of the list.

This lockstep approach will generally give better cache utilization, because a node hit by the front pointer may still be in cache when the rear pointer reaches it. In a language implementation using tracing garbage collection, this approach also avoids unnecessarily keeping the beginning (thus entire) list live for the duration of the operation.

Another solution is to use circular buffer . Keep a circular buffer of size x and add the nodes to it as you traverse the list. When you reach the end of the list, the x'th one from the tail is equal to the next entry in the circular buffer.

The lockstep approach moves all array elements in every step, resulting in a O(n + x 2 ) running time, whereas circular buffer approach uses a circular array and runs in O(n) . The circular buffer solution requires an additional x in memory.

Circular buffer approach:

Q22 :   How to merge two sorted Arrays into a Sorted Array ?

Let's look at the merge principle :

Given two separate lists A and B ordered from least to greatest, construct a list C by:

  • repeatedly comparing the least value of A to the least value of B,
  • removing (or moving a pointer) the lesser value, and appending it onto C.
  • when one list is exhausted, append the remaining items in the other list onto C in order.
  • The list C is then also a sorted list.

Space: None

This problem will have O(n) complexity at best.

Q23 :   Implement Double Linked List from Stack with min complexity

Imagine all items are organized into two stacks, draw them facing each other where face is where you put and peek:

now you can move 4 to 5:

and 3 to 4:

and you can go backwards.

You may also need another two stacks so that you can traverse List via the tail:

once current stack runs out

simply switch to the second pair of stacks!

Q24 :   Merge two sorted singly Linked Lists without creating new nodes

You have two singly linked lists that are already sorted, you have to merge them and return a the head of the new list without creating any new extra nodes. The returned list should be sorted as well.

The method signature is:

Node class is below:

Here is the algorithm on how to merge two sorted linked lists A and B:

Here C will be the output list.

There are two solutions possible:

  • Of the two nodes passed, keep the node with smaller value
  • Point the smaller node's next to the next smaller value of remaining of the two linked lists
  • Return the current node (which was smaller of the two nodes passed to the method)
  • Treat one of the sorted linked lists as list, and treat the other sorted list as `bag of nodes'.
  • Then we lookup for correct place for given node (from bag of nodes) in the list.

The run time complexity for the recursive and iterative solution here or the variant is O ( n ) .

Recursive solution:

Recursion should not be needed to avoid allocating a new node:

Q25 :   Remove Invalid Parentheses

We all know how to check a string of parentheses is valid using a stack. Or even simpler use a counter. The counter will increase when it is ( and decrease when it is ) . Whenever the counter is negative, we have more ) than ( in the prefix.

To make the prefix valid, we need to remove a ) . The problem is: which one? The answer is any one in the prefix. However, if we remove any one, we will generate duplicate results, for example: s = ()), we can remove s[1] or s[2] but the result is the same (). Thus, we restrict ourself to remove the first ) in a series of concecutive )s.

After the removal, the prefix is then valid. We then call the function recursively to solve the rest of the string. However, we need to keep another information: the last removal position. If we do not have this position, we will generate duplicate by removing two ) in two steps only with a different order. For this, we keep tracking the last removal position and only remove ) after that.

Now one may ask. What about ( ? What if s = (()(() in which we need remove ( ? The answer is: do the same from right to left. However a cleverer idea is: reverse the string and reuse the code!

Q26 :   Sort a Stack using Recursion

Note we can't use another stack or queue.

The idea of the solution is to hold all values in system stack until the stack becomes empty. When the stack becomes empty, insert all held items one by one in sorted order.

Time: O(n^2)

Q27 :   Sort a Stack using another Stack

A stack performs push and pop operations. So, the push and pop operations are carried out between the input_stack and the auxilary_stack in such a way that the auxiliary stack contains the sorted input stack.

Solution Steps:

  • Create a temporary stack say aux_stack .
  • Repeat until the input_stack is not empty
  • Pop an element from input_stack call it temp_value.
  • While aux_stack is not empty and top of the aux_stack < temp_value , pop data from aux_stack and push it to the input_stack
  • Push temp_value to the aux_stack
  • return the aux_stack .

Q28 :   Write a program for Recursive Binary Search

  • The first difference is that the while loop from iterative approach is replaced by a recursive call back to the same method with the new values of low and high passed to the next recursive invocation along with Array and key or target element.
  • The second difference is that instead of returning false when the while loop exits in the iterative version, in case of the recursive version, the condition of low > high is checked at the beginning of the next level of recursion and acts as the boundary condition for stopping further recursive calls by returning false.
  • Also, note that the recursive invocations of binarySearch() return back the search result up the recursive call stack so that true or false return value is passed back up the call stack without any further processing.
  • To further optimize the solution, in term of running time, we could consider implement the tail-recursive solution , where the stack trace of the algorithm would not pile up, which leads to a less memory footprint during the running time. To have the tail-recursive solution, the trick is to simply return the result from the next recursive function instead of further processing.

Q29 :   Explain Knuth-Morris-Pratt (KMP) Algorithm in Plain English

The KMP algorithm is an efficient string matching algorithm due to Donald Knuth, Vaughan Pratt, and James H. Morris.

For the string matching problem (find p in S ) the naive approach would be to slide a window of size p all over S and check if it matches. That works but actually is inefficient. It takes O(p*S) time.

Instead of naive approach KMP is a linear time ( O ( n ) ) algorithm that exploits the observation that every time a match (or a mismatch) happens, the pattern itself contains enough information to dictate where the new examination should begin from. Every time the naive function fails (or succeeds), it starts matching over from the next character. This might not be necessary. We could use our knowledge of the point of last matching and the "structure" of the test string to know where the next matching should begin from.

How To Understand Prefix Function and Partial Match Table?

The "structure" of the string is encapsulated in the Prefix (or Failure) Function that we use to create Partial Match Table . Now, in order to talk about the meaning, we need to know about proper prefixes and proper suffixes.

  • Proper prefix : All the characters in a string, with one or more cut off the end. “S”, “Sn”, “Sna”, and “Snap” are all the proper prefixes of “Snape”.
  • Proper suffix : All the characters in a string, with one or more cut off the beginning. “agrid”, “grid”, “rid”, “id”, and “d” are all proper suffixes of “Hagrid”.

Saying that here’s the partial match table for the pattern abababca where each cell value is "The length of the longest proper prefix in the (sub)pattern that matches a proper suffix in the same (sub)pattern" .

Let’s also try it for cell five, which concerns “ababa”. We have four proper prefixes (“a”, “ab”, “aba”, and “abab”) and four proper suffixes (“a”, “ba”, “aba”, and “baba”). Now, we have two matches: “a” and “aba” are both proper prefixes and proper suffixes. Since “aba” is longer than “a”, it wins, and cell five gets value 3.

How To Use Partial Match Table?

We can use the values in the partial match table to skip ahead (rather than redoing unnecessary old comparisons) when we find partial matches. The formula works like this:

If a partial match of length partial_match_length is found and table[partial_match_length] > 1 , we may skip ahead partial_match_length - table[partial_match_length - 1] characters.*

Let’s say we’re matching the pattern “abababca” against the text “bacbababaabcbab”. Here’s our partial match table again for easy reference:

The first time we get a partial match is here:

This is a partial_match_length of 1. The value at table[partial_match_length - 1] (or table[0] ) is 0, so we don’t get to skip ahead any. The next partial match we get is here:

This is a partial_match_length of 5. The value at table[partial_match_length - 1] (or table[4] ) is 3. That means we get to skip ahead partial_match_length - table[partial_match_length - 1] (or 5 - table[4] or 5 - 3 or 2 ) characters:

This is a partial_match_length of 3. The value at table[partial_match_length - 1] (or table[2] ) is 1. That means we get to skip ahead partial_match_length - table[partial_match_length - 1] (or 3 - table[2] or 3 - 1 or 2 ) characters:

At this point, our pattern is longer than the remaining characters in the text, so we know there’s no match.

Things to remember:

  • Once table is built, this algorithm has complexity O(n) even for binary alphabet (compare with O(m*n) for brute force).
  • Table is built very quickly at start since pattern is usually very small.
  • Table-building part is O(m) . Search part is O(n) . Total complexity O(m+n) even on binary alphabet.
  • Compare with O(m*n) for brute force on binary alphabet.
  • Because the prefix-function already tells us what needs to be done about the already matched parts, we do not need to check those parts again and hence, only one pass over the string is sufficient. So, the time complexity of the matching is O ( n ) .
  • What about the pre-computation? It turns out that, if correctly implemented, it can be done in O(m) time where m is a length of a pattern.
  • Overall, it takes O(m+ n) time. But since m≤ n , the time is bounded by O(n) . This is certainly better than the usual O ( n 2 )
  • We only require as much space as the pattern. So, the space requirement is O(m) .

Q30 :   Find Merge (Intersection) Point of Two Linked Lists

Say, there are two lists of different lengths, merging at a point ; how do we know where the merging point is?

Conditions:

  • We don't know the length

This arguably violates the "parse each list only once" condition, but implement the tortoise and hare algorithm (used to find the merge point and cycle length of a cyclic list) so you start at List 1, and when you reach the NULL at the end you pretend it's a pointer to the beginning of List 2, thus creating the appearance of a cyclic list. The algorithm will then tell you exactly how far down List 1 the merge is.

Algorithm steps:

  • it goes forward every time till the end, and then
  • jumps to the beginning of the opposite list, and so on.
  • Create two of these, pointing to two heads.
  • Advance each of the pointers by 1 every time, until they meet in intersection point ( IP ). This will happen after either one or two passes.

To understand it count the number of nodes traveled from head1-> tail1 -> head2 -> intersection point and head2 -> tail2-> head1 -> intersection point . Both will be equal (Draw diff types of linked lists to verify this). Reason is both pointers have to travel same distances head1-> IP + head2->IP before reaching IP again. So by the time it reaches IP , both pointers will be equal and we have the merging point.

Q31 :   Flip k least significant bits in an integer

The ~ unary operator is bitwise negation. If you need fewer bits than what fits in an int then you'll need to mask it with & after the fact.

To flip the k least significant bits, use the right mask.

or you can create a mask without loop:

Q32 :   Given a singly Linked List, determine if it is a Palindrome

Could you do it in O ( 1 ) time and O ( 1 ) space?

Solution: is Reversed first half == Second half ?

Let's look to an example [1, 1, 2, 1] . In the beginning, set two pointers fast and slow starting at the head.

(1) Move: fast pointer goes to the end, and slow goes to the middle.

(2) Reverse: the right half is reversed, and slow pointer becomes the 2nd head.

(3) Compare: run the two pointers head and slow together and compare.

Q33 :   How come that hash values are not reversible?

The input material can be an infinite length, where the output is always 128 bits long (for MD5 hash). This means that an infinite number of input strings will generate the same output.

If you pick a random number and divide it by 2 but only write down the remainder, you'll get either a 0 or 1 - even or odd, respectively. Is it possible to take that 0 or 1 and get the original number?

Q34 :   How implement a Queue using only One (1) Stack?

I know how to do that with 2 stacks but how to implement it with one?

Tricky question.

You can "cheat" by using recursive function calls to pop the stack, then you push the item being queued, then as the recursive calls unwind you push what was popped. But this is really two stacks, because the function call stack counter is a stack .

Following is the implementation:

  • During Enqueue operation, we can straight away push the element into the stack.

During Dequeue operation,

  • Pop all the elements from a Stack recursively until Stack size is equal to 1 .
  • If Stack size = 1 , Pop item from Stack , and return the same item.
  • Push all popped element back to Stack .

Q35 :   How to implement 3 Stacks with one Array ?

Find an algorithm/write pseudocode with high performance for a stack with only two operations, pop() and push() .

Space (not time) efficient. You could:

  • Define two stacks beginning at the array endpoints and growing in opposite directions.
  • Define the third stack as starting in the middle and growing in any direction you want.
  • Redefine the Push op, so that when the operation is going to overwrite other stack, you shift the whole middle stack in the opposite direction before Pushing.

You need to store the stack top for the first two stacks, and the beginning and end of the third stack in some structure.

Above you may see an example. The shifting is done with an equal space partitioning policy, although other strategies could be chosen depending upon your problem heuristics.

the middle stack could be implemented using an alternating sequence for subsequent pushes. The resulting stack structure will be something like:

In this case, you'll need to store the number n of elements on the middle stack and use the function:

to know the next array element to use for this stack.

Although probably this will lead to less shifting, the implementation is not homogeneous for the three stacks, and inhomogeneity (you know) leads to special cases, more bugs and difficulties to maintain code.

Q36 :   How to recursively reverse a Linked List?

Start from the bottom up by asking and answering tiny questions:

  • What is the reverse of null (the empty list)? null .
  • What is the reverse of a one element list? the element.
  • What is the reverse of an n element list? the reverse of the rest of the list followed by the first element.

How to understand that part?

Think about the origin link list:

Now assume that the last node has been reversed. Just like this:

And this time you are at the node 3 , you want to change 3->4 to 3<-4 , means let 3->next->next = 3 (as 3->next is 4 and 4->next = 3 is to reverse it)

Assume that n is the list's length, the time complexity is O ( n ) . The extra space comes from implicit stack space due to recursion. The recursion could go up to n levels deep then space complexity is O ( n ) .

Q37 :   How to use Memoization for N-th Fibonacci number?

Why? Any problems you may face with that solution?

Yes. It's called Memoization . Memoization is an optimization technique used primarily to speed up computer programs by storing the results of expensive function calls .

Let’s look at the diagram that will help you understand what’s going on here with the rest of our code. Function fib is called with argument 5. Can you see that we calculate the fib(2) results 3(!) times?

Basically, if we just store the value of each index in a hash , we will avoid the computational time of that value for the next N times. This change will increase the space complexity of our new algorithm to O ( n ) but will dramatically decrease the time complexity to 2N which will resolve to linear time since 2 is a constant O ( n ) .

There’s just one problem : With an infinite series, the memo array will have unbounded growth. Eventually, you’re going to run into heap size limits, and that will crash the JS engine. No worries though. With Fibonacci, you’ll run into the maximum exact JavaScript integer size first, which is 9007199254740991 . That’s over 9 quadrillion, which is a big number, but Fibonacci isn’t impressed. Fibonacci grows fast . You’ll burst that barrier after generating only 79 numbers.

Q38 :   Copy a Linked List with Random (Arbitrary) Pointer using O ( 1 ) Space

Every node of the linked list has a random pointer (in addition to the next pointer) which could randomly point to another node or be null. How would you duplicate such a Linked List? Could you do that in O ( 1 ) space complexity?

Let's assume you have

An intuitive solution is to keep a hash table for each node in the list, via which we just need to iterate the list in 2 rounds ( 2N steps) respectively to create nodes and assign the values for their random pointers. As a result, the space complexity of this solution is O(N) , although with a linear time complexity.

  • Walk the old list following the next pointers. For each node you visit, add a node to your new list, connect the previous node in your new list to the new node, store the old node random pointer in the new new node, then store a mapping of the old node pointer to the new node pointer in a map .
  • Walk the new list, and for each random pointer, look it up in the map to find the associated node in the new list to replace it with.

As an optimised solution, we could reduce the space complexity into constant. The idea is to associate the original node with its copy node in a single linked list. In this way, we don't need extra space to keep track of the new nodes.

The algorithm is composed of the follow three steps which are also 3 iteration rounds.

  • Iterate the original list and duplicate each node. The duplicate of each node follows its original immediately.
  • Iterate the new list and assign the random pointer for each duplicated node.
  • Restore the original list and extract the duplicated nodes.

Or mapped to code below:

Hash table version:

Q39 :   Find all the repeating substrings in a given String (or DNA chromosome sequence)

Suffix Tree is the way to go.

  • If you analyze the output for the string "AAAAAAAAAAAAAA" , then there are O ( n 2 ) characters in it, so the algorithm is at least O ( n 2 ) .
  • To achieve O ( n 2 ) , just build the suffix tree for each suffix of s (indices 1..n , 2..n , 3..n , ..., n..n ). It doesn't matter if one of the strings has no own end node, just count how often each node is used.
  • At the end, iterate over each node with count > 1 and print its path.

There are multiple way to construct the suffix tree:

  • Using Ukkonen's algorithm.
  • Using Suffix array and LCP (longest common prefix array)

Q40 :   How to check for braces balance in a really large (1T) file in parallel?

There is a large file( 1TB) containing braces. How to check for braces balance? Make this process parallel.

If ( = 1 and ) = -1 . We should check the same two conditions:

  • The total sum of the brackets is 0
  • We never go negative at any point of time.

The first instinct to solving the parallel problem might be to split the work up into equal-sized chunks for each processor. If there are N characters in the file and K processors, give each processor a chunk of N/K characters. When processing a chunk, we can no longer simply return false when the count drops below 0, because there may be more opening braces in an earlier chunk processed by a different processor. We also can't return false if the counter is not 0 at the end, because it may be that there are more closing braces in later chunks. What we should calculate for each chunk, instead, is:

If we were doing a global brace counter as in the single-threaded approach, by how much would this chunk change the counter? This can be a positive or negative number. Call this the " brace delta ". This number is equal to the number of opening braces minus the number of closing braces in the chunk.

While we are calculating the " brace delta ", what is the lowest point to which the brace delta drops anytime during the processing of the chunk? Call that the " brace delta minimum ". This number is important because this is the point in the chunk where the global counter would be the smallest. We can check whether the global counter would have ever been negative by seeing whether (global counter before chunk) + (brace delta minimum in chunk) < 0 for any chunk.

These two things would be calculated by:

The complexity of the above code is O(N/K) for each of K processors. However, we can consider it O(N/K) time because all the processors can work in parallel.

After we process each chunk in parallel, we combine the results in a single-threaded way. We use the brace deltas to calculate the value of the global counter at the beginning of every chunk, and we use the brace delta min of the chunks to verify that the global counter never drops below 0. The global counter value should be 0 at the end of all the chunks as before.

The non-parallel part takes O(K) time, making the overall time for the solution O(N/K + K) .

Rust has been Stack Overflow’s most loved language for four years in a row and emerged as a compelling language choice for both backend and system developers, offering a unique combination of memory safety, performance, concurrency without Data races...

Clean Architecture provides a clear and modular structure for building software systems, separating business rules from implementation details. It promotes maintainability by allowing for easier updates and changes to specific components without affe...

Azure Service Bus is a crucial component for Azure cloud developers as it provides reliable and scalable messaging capabilities. It enables decoupled communication between different components of a distributed system, promoting flexibility and resili...

FullStack.Cafe is a biggest hand-picked collection of top Full-Stack, Coding, Data Structures & System Design Interview Questions to land 6-figure job offer in no time.

Coded with 🧡 using React in Australia 🇦🇺

by @aershov24 , Full Stack Cafe Pty Ltd 🤙, 2018-2023

Privacy • Terms of Service • Guest Posts • Contacts • MLStack.Cafe

problem solving programming questions

Codemonk

  • Basics of Input/Output
  • Time and Space Complexity
  • Basics of Implementation
  • Basics of Operators
  • Basics of Bit Manipulation
  • Recursion and Backtracking
  • Multi-dimensional
  • Basics of Stacks
  • Basics of Queues
  • Basics of Hash Tables
  • Singly Linked List
  • Binary/ N-ary Trees
  • Binary Search Tree
  • Heaps/Priority Queues
  • Trie (Keyword Tree)
  • Segment Trees
  • Fenwick (Binary Indexed) Trees
  • Suffix Trees
  • Suffix Arrays
  • Basics of Disjoint Data Structures
  • Linear Search
  • Binary Search
  • Ternary Search
  • Bubble Sort
  • Selection Sort
  • Insertion Sort
  • Counting Sort
  • Bucket Sort
  • Basics of Greedy Algorithms
  • Graph Representation
  • Breadth First Search
  • Depth First Search
  • Minimum Spanning Tree
  • Shortest Path Algorithms
  • Flood-fill Algorithm
  • Articulation Points and Bridges
  • Biconnected Components
  • Strongly Connected Components
  • Topological Sort
  • Hamiltonian Path
  • Maximum flow
  • Minimum Cost Maximum Flow
  • Basics of String Manipulation
  • String Searching
  • Z Algorithm
  • Manachar’s Algorithm
  • Introduction to Dynamic Programming 1
  • 2 Dimensional
  • State space reduction
  • Dynamic Programming and Bit Masking
  • Basic Number Theory-1
  • Basic Number Theory-2
  • Primality Tests
  • Totient Function
  • Basics of Combinatorics
  • Inclusion-Exclusion
  • Line Sweep Technique
  • Line Intersection using Bentley Ottmann Algorithm
  • Basic Probability Models and Rules
  • Bayes’ rules, Conditional probability, Chain rule
  • Discrete Random Variables
  • Continuous Random Variables
  • Practical Tutorial on Data Manipulation with Numpy and Pandas in Python
  • Beginners Guide to Regression Analysis and Plot Interpretations
  • Practical Guide to Logistic Regression Analysis in R
  • Practical Tutorial on Random Forest and Parameter Tuning in R
  • Practical Guide to Clustering Algorithms & Evaluation in R
  • Beginners Tutorial on XGBoost and Parameter Tuning in R
  • Deep Learning & Parameter Tuning with MXnet, H2o Package in R
  • Decision Tree
  • Simple Tutorial on Regular Expressions and String Manipulations in R
  • Practical Guide to Text Mining and Feature Engineering in R
  • Winning Tips on Machine Learning Competitions by Kazanova, Current Kaggle #3
  • Practical Machine Learning Project in Python on House Prices Data
  • Challenge #1 - Machine Learning
  • Challenge #3 - Machine Learning
  • Challenge #2 - Deep Learning
  • Transfer Learning Introduction
  • Input and Output
  • Python Variables
  • Conditionals
  • Expressions
  • Classes and Objects I
  • Classes and Objects II (Inheritance and Composition)
  • Errors and Exceptions
  • Iterators and Generators
  • Functional Programming
  • Higher Order Functions and Decorators
  • +1-650-461-4192
  • For sales enquiry [email protected]
  • For support [email protected]
  • Campus Ambassadors
  • Assessments
  • Learning and Development
  • Interview Prep
  • Engineering Blog
  • Privacy Policy
  • © 2024 HackerEarth All rights reserved
  • Terms of Service
  • Trending Now
  • Foundational Courses
  • Data Science
  • Practice Problem
  • Machine Learning
  • System Design
  • DevOps Tutorial

Basic Programming Problems

  • Learn Programming For Free
  • Programming Tutorial | Introduction, Basic Concepts, Getting started, Problems
  • Types of Issues and Errors in Programming/Coding
  • What is Programming? A Handbook for Beginners
  • Top 10 Programming Tips For Beginners
  • C++ Programming Examples
  • Best Courses on Competitive Programming
  • CBSE Class 11 | Concepts of Programming Methodology
  • How to begin with Competitive Programming?
  • Programming | Question 1
  • CBSE Class 11 | Problem Solving Methodologies
  • C Program to Add Two Integers
  • Top | MCQs on Dynamic Programming with Answers | Question 19
  • C++ program for Solving Cryptarithmetic Puzzles
  • Basic Coding Problems in DSA for Beginners
  • Output of C programs | Set 49 (Operators)
  • C Program to Make a Simple Calculator
  • C | Pointer Basics | Question 13
  • Program to print ASCII Value of a character
  • Introduction of Programming Paradigms
  • Program for Hexadecimal to Decimal
  • Program for Decimal to Octal Conversion
  • A Freshers Guide To Programming
  • ASCII Vs UNICODE
  • How to learn Pattern printing easily?
  • Loop Unrolling
  • How to Learn Programming?
  • Program to Print the Trapezium Pattern

Learn Programming – How To Code

In the world of programming , mastering the fundamentals is key to becoming a proficient developer. In this article, we will explore a variety of basic programming problems that are essential for every aspiring coder to understand. By delving into these foundational challenges, you will gain valuable insights into problem-solving techniques and build a strong foundation for your programming journey. Whether you’re a novice programmer or looking to refresh your skills, this guide will provide you with a solid introduction to essential programming problems

Why to Start with Basics Programming Problems?

Starting with basics is important because it helps you build a strong foundation. When you understand the basics well, it becomes easier to learn more advanced things later on. It’s like building a solid base for a tall building – if the base is strong, the building will be strong too. Mastering the basics also helps you become better at solving problems, which is really important in programming and other technical areas.

Benefits of Starting with Basic Programming Problems:

Foundation Building: Establishes a strong foundation in coding by introducing fundamental concepts.

  • Improve Problem-Solving: Enhances problem-solving skills, preparing for more complex challenges.
  • Language Proficiency: Fosters proficiency in a programming language, facilitating expression of thoughts and implementation of solutions.
  • Debugging Skills: Provides practice in debugging techniques and understanding common errors.
  • Algorithmic Thinking: Encourages efficient and optimized thinking, laying the groundwork for advanced problem-solving.
  • Confidence Building: Boosts confidence in coding and problem-solving abilities through successful progression.
  • Get Ready for Interviews: Prepares for coding job interviews by mastering fundamental concepts commonly assessed.

Basic Programming Problems:

Related Article:

  • What is a Code in Programming?
  • What Is Coding and What Is It Used For?

Please Login to comment...

Similar reads.

  • Programming

advertisewithusBannerImg

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

The 10 Most Popular Coding Challenge Websites [Updated for 2021]

Daniel Borowski

A great way to improve your skills when learning to code is by solving coding challenges. Solving different types of challenges and puzzles can help you become a better problem solver, learn the intricacies of a programming language, prepare for job interviews, learn new algorithms, and more.

Below is a list of some popular coding challenge websites with a short description of what each one offers.

1. TopCoder

MTryRL4uVza1V87ERWY26L4cFeqD2rgAnW1f

TopCoder is one of the original platforms for competitive programming online. It provides a list of algorithmic challenges from the past that you can complete on your own directly online using their code editor. Their popular Single Round Matches are offered a few times per month at a specific time where you compete against others to solve challenges the fastest with the best score.

The top ranked users on TopCoder are very good competitive programmers and regularly compete in programming competitions. The top ranked user maintains his own blog titled Algorithms weekly by Petr Mitrichev where he writes about coding competitions, algorithms, math, and more.

2. Coderbyte

sP6ow4n2alliqp5L-p5fVRQC9W0GTws1B9Ig

Coderbyte provides 200+ coding challenges you can solve directly online in one of 10 programming languages (check out this example ). The challenges range from easy (finding the largest word in a string) to hard (print the maximum cardinality matching of a graph).

They also provide a collection of algorithm tutorials , introductory videos, and interview preparation courses . Unlike HackerRank and other similar websites, you are able to view the solutions other users provide for any challenge aside from the official solutions posted by Coderbyte.

3. Project Euler

plhA-E3btLLYRvc4hi3WxmUpAhu3aoef1o0V

Project Euler provides a large collection of challenges in the domain of computer science and mathematics. The challenges typically involve writing a small program to figure out the solution to a clever mathematical formula or equation, such as finding the sum of digits of all numbers preceding each number in a series.

You cannot directly code on the website in an editor, so you would need to write a solution on your own computer and then provide the solution on their website.

4. HackerRank

dOpMtufto0gLZiyDOHZ4BVF58S-z393wRlcu

HackerRank provides challenges for several different domains such as Algorithms, Mathematics, SQL, Functional Programming, AI, and more. You can solve all the challenge directly online (check out this example ).

They provide a discussion and leaderboard for every challenge, and most challenges come with an editorial that explains more about the challenge and how to approach it to come up with a solution.

Currently, if you don't solve the problem, then you can't see the solution of others. If you also try to check the editorial before solving the problem, then you won't get the point for solving the problem at all.

As an example, here I haven't solved the problem, and I am trying to check others' submissions:

problem-not-solved-yet

And here, I haven't solved the problem, and I am trying to check the editorial:

problem-not-solved-lost-point

HackerRank also provides the ability for users to submit applications and apply to jobs by solving company-sponsored coding challenges.

5. CodeChef

81eunsDYPAqBSC8KwPpBxhPFTHiqGXp70kMa

CodeChef is an Indian-based competitive programming website that provides hundreds of challenges. You are able to write code in their online editor and view a collections of challenges that are separated into different categories depending on your skill level (check out this example ). They have a large community of coders that contribute to the forums, write tutorials , and take part in CodeChef’s coding competitions .

6. Exercism.io

Screen-Shot-2019-12-11-at-8.14.45-AM

Exercism is a coding challenge website that offers 3100+ challenges spanning 52 different programming languages. After picking a language that you'd like to master, you tackle the coding challenges right on your machine (Exercism has their own command line interface that you can download from GitHub).

It is a bit different from other challenge websites, however, because you work with a mentor after completing each challenge. The mentor reviews your answers online and helps you improve them if needed. Once your answers have been approved and submitted, you unlock more challenges.

7. Codewars

QR7cVhZ7FGb6HjaEDu4N5Co1eTMNTbo1JFzq

Codewars provides a large collection of coding challenges submitted and edited by their own community. You can solve the challenges directly online in their editor in one of several languages. You can view a discussion for each challenges as well as user solutions.

8. LeetCode

RzWKVwPaLY2SRsWFWk93ZNlzcg8V0Yeav5t7

LeetCode is a popular Online Judge that provides a list of 190+ challenges that can help you prepare for technical job interviews. You can solve the challenges directly online in one of 9 programming languages. You are not able to view other users' solutions, but you are provided statistics for your own solutions such as how fast your code ran when compared to other users' code.

They also have a Mock Interview section that is specifically for job interview preparation, they host their own coding contests , and they have a section for articles to help you better understand certain problems.

MF3wP06V24C7jal2f8NRvAVhS-tAA2vbNDTL

Sphere Online Judge (SPOJ) is an online judge that provides over 20k coding challenges. You are able to submit your code in an online editor . SPOJ also hosts their own contests and has an area for users to discuss coding challenges. They do not currently provide any official solutions or editorials like some other websites do, though.

10. CodinGame

6l08ZCKDOaoY1TH-PHHHac26McA-c1tIDOPU

CodinGame is a bit different from the other websites, because instead of simply solving coding challenges in an editor, you actually take part in writing the code for games that you play directly online. You can see a list of games currently offered here and an example of one here . The game comes with a problem description, test cases, and an editor where you can write your code in one of 20+ programming languages.

Although this website is different than typical competitive programming websites such as the ones mentioned above, it is still popular amongst programmers who enjoy solving challenges and taking part in contests.

This list was based on a few things: my own experiences using the websites, some Google searches , Quora posts , and articles such as this one and this one . I also frequented some forums and subreddits such as r/learnprogramming to see what websites were usually recommended by the users there. Disclaimer: I work at Coderbyte which is one of the websites mentioned above.

CEO & Founder at Coderbyte.

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

PW Skills | Blog

75 Basic Programming Problems and Tutorials for Practice

' src=

Varun Saharawat is a seasoned professional in the fields of SEO and content writing. With a profound knowledge of the intricate aspects of these disciplines, Varun has established himself as a valuable asset in the world of digital marketing and online content creation.

Solving Basic Programming Problems is the key to achieve success in coding challenges. Students must practice these basic programming problems!

basic programming problems

Basic Programming Problems: Engaging in code challenges offers many benefits, serving as a dynamic tool to enhance problem-solving proficiency, deepen your comprehension of the programming language you work with, and acquaint yourself with diverse algorithms. If you aspire to elevate your programming skills, immersing yourself in coding is the most effective avenue.

The beauty of basic programming problems lies in their convenience—they provide a platform to hone your abilities through bite-sized problems, often eliminating the need to construct entire applications. This characteristic allows you to conquer these challenges swiftly, fostering a sense of accomplishment.

Moreover, code challenges are integral components of many coding interviews.

While your resume may showcase your skills and ability to articulate programming concepts, employers want to validate your practical coding capabilities. Tackling coding challenges during interviews becomes a testament to your proficiency and showcases your competence for the role.

Therefore, incorporating coding challenges into your routine sharpens your skills and is an invaluable preparation strategy for job interviews. To kickstart your coding journey, we have curated a collection of popular basic programming problems to pave the way for your continued growth.

Table of Contents

Recommended Technical Course

  • Full Stack Development Course
  • Generative AI Course
  • DSA C++ Course
  • Data Analytics Course
  • Python DSA Course
  • DSA Java Course

Basic Programming Problems Overview

Basic programming problems provide an essential foundation for individuals learning to code, offering a practical and hands-on approach to mastering fundamental concepts in programming.

These problems are designed to introduce beginners to the core coding principles, gradually building their problem-solving skills and comprehension of programming logic.

Whether you are a novice looking to embark on your coding journey or an experienced programmer aiming to reinforce your foundational knowledge, engaging with basic programming problems is a valuable practice.

These problems typically cover essential topics such as data types, loops, conditionals, functions, and basic algorithms, providing a well-rounded introduction to the key building blocks of programming.

The significance of basic programming problems extends beyond mere skill development; it serves as a stepping stone for individuals aspiring to pursue more advanced coding challenges and projects.

By grappling with these foundational problems, learners can cultivate a solid understanding of programming fundamentals, laying the groundwork for future exploration and mastery of more complex coding concepts. Basic programming problems are the cornerstone of a programmer’s educational journey, fostering a strong and resilient coding skill set.

Basic Programming Problems for Beginners

Starting your career in the programming field is  exciting and challenging. For beginners, mastering the basics is crucial, and what better way to do so than by solving basic programming problems ?

Basic Programming Problems Java

Here are some of the basic programming problems JAVA :

1) Hello World:

public class HelloWorld {

    public static void main(String[] args) {

        System.out.println(“Hello, World!”);

2) The sum of Two Numbers:

Add two numbers and print the result.

public class Sum {

        int num1 = 5, num2 = 10, sum;

        sum = num1 + num2;

        System.out.println(“Sum: ” + sum);

3) Factorial of a Number:

Calculate the factorial of a number.

public class Factorial {

        int num = 5;

        long factorial = 1;

        for (int i = 1; i <= num; ++i) {

            factorial *= i;

        System.out.println(“Factorial: ” + factorial);

4) Check Even or Odd:

Determine if a number is even or odd.

public class EvenOdd {

        int num = 8;

        if (num % 2 == 0) {

            System.out.println(num + ” is even.”);

        } else {

            System.out.println(num + ” is odd.”);

5) Reverse a String:

Reverse the characters in a given string.

public class ReverseString {

        String str = “Hello”;

        StringBuilder reversed = new StringBuilder(str).reverse();

        System.out.println(“Reversed String: ” + reversed);

Here are some theory-based basic programming problems Java:

1) Differences Between C++ and Java

  • C++: Not platform-independent, follows “write once, compile anywhere.”
  • Java: Platform-independent byte code allows programs to run on any machine.

Languages Compatibility:

  • C++: Compatible with most high-level languages.
  • Java: Incompatible with most languages, comparable to C and C++.

Interaction with the Library:

  • C++: Direct access to native system libraries, suitable for system-level programming.
  • Java: Requires Java Native Interface or library access, not direct call support.

Characteristics:

  • C++: Combines features of procedural and object-oriented languages.
  • Java: Known for automatic garbage collection, lacks support for destructors.

Semantics of the Type:

  • C++: Consistent semantics for primitive and object types.
  • Java: Inconsistent semantics between primitive and object types and classes.

Compiler and Interpreter:

  • Java: Compiled and interpreted language, source code compiles into platform-independent bytecode.
  • C++: Purely compiled language, source program compiles into object code, further executed.

2) Features of the Java Programming Language:

  • Easy: Java is considered easy to learn, with fundamental Object-Oriented Programming (OOP) concepts.
  • Secured Feature: Java provides a secured feature, ensuring the development of virus-free and tamper-free systems.
  • OOP: Java follows Object-Oriented Programming, treating everything as an object.
  • Independent Platform: Java compiles into platform-independent bytecode, interpreted by the Virtual Machine.

3) ClassLoader in Java:

  • A ClassLoader in Java is a subsystem of the Java Virtual Machine responsible for loading class files during program execution.
  • It is the first to load the executable file and includes Bootstrap, Extension, and Application classloaders.

4) Differences Between Heap and Stack Memory in Java:

  • Stack Memory: Allocated to each individual program. Fixed memory space.
  • Heap Memory: Not assigned to Java code initially but available during runtime. Used as needed by the Java code.

Embark on a transformative journey with our comprehensive course, “ Decode Java+DSA 1.0 ,” meticulously designed to empower you with the skills needed to excel in programming. This course seamlessly integrates Core Java and Data Structures and Algorithms (DSA), offering a holistic learning experience that lays a robust foundation for your programming journey.

Key Features:

  • Comprehensive Java Coverage: Delve into the intricacies of Core Java, unraveling the language’s syntax, features, and object-oriented programming concepts. From basic constructs to advanced topics, this course ensures a thorough understanding of Java.
  • Powerful Problem-Solving with DSA: Unlock the potential of Data Structures and Algorithms to efficiently solve complex problems. Acquire the essential tools and strategies to approach real-world challenges with confidence and precision.
  • Hands-On Learning: Immerse yourself in practical, hands-on exercises that reinforce theoretical concepts. Through coding exercises and projects, you’ll apply your knowledge, fostering a deeper understanding of both Java and DSA.
  • Expert Guidance: Benefit from expert guidance provided by seasoned instructors with extensive industry experience. Learn industry best practices and gain insights into the practical applications of Java and DSA.

Who Should Enroll:

  • Programming Enthusiasts
  • Students Pursuing Computer Science or Related Fields
  • Professionals Seeking to Strengthen Core Java and DSA Skills

Upon completion of “ Decode Java+DSA 1.0 ,” by PW you’ll emerge as a proficient programmer equipped with the skills to tackle diverse programming challenges. Whether you’re aiming to kickstart your programming career, enhance your academic pursuits, or upskill for professional growth, this course is your gateway to mastering Java and DSA. Elevate your programming prowess and embark on a journey of continuous learning and innovation.

Basic Programming Problems in C

The table below shows the basic programming problems in C :

Put your learning into action with hands-on projects that simulate real-world scenarios with Decode Full Stack Web Dev 1.0 by PW . From designing responsive user interfaces to implementing robust server-side functionalities, you’ll gain practical experience that enhances your proficiency.

Learn essential tools like Git for version control, ensuring collaborative and efficient development. Explore deployment strategies to showcase your applications to the world, covering platforms like Heroku.

Who Should Enroll

  • Aspiring Web Developers 
  • Computer Science Students 
  • Professionals Transitioning to Web Development 
  • Entrepreneurs Looking to Build Web Applications

Basic Programming Problems in Python

In addition to introducing you to Python’s syntax and structure, tackling basic programming problems in Python helps you improve your problem-solving skills. With tasks ranging from basic logic puzzles to intricate algorithmic difficulties, these issues offer an interactive method of learning Python and put you on the route to becoming a skilled programmer.

Basic Programming Problems in Javascript

Whether you aim to enhance your web development skills or explore the vast world of JavaScript applications, these problems cater to beginners, guiding them through the foundational aspects of programming in this versatile language. Below table showcases the basic programming problems in Javascript :

Embark on a transformative learning experience with our comprehensive course, “Building MicroServices in Java for Cloud .”

Key Highlights

  • Microservices Fundamentals: Gain a solid understanding of microservices architecture, learning how to decompose large applications into smaller, independently deployable services. Explore the principles and benefits that drive the adoption of microservices in modern software development.
  • Java for Microservices : Leverage the power of Java to build robust microservices. Explore Java frameworks and libraries that facilitate the development of scalable and efficient microservices, ensuring seamless integration with cloud platforms.
  • Communication Strategies: Delve into various communication patterns and protocols essential for microservices interactions. Learn about RESTful APIs, messaging queues, and other communication mechanisms used to establish seamless communication between microservices.
  • Software Developers and Engineers
  • System Architects
  • Cloud Enthusiasts
  • Java Developers Exploring Microservices

Basic Programming Problems and Solutions

Here are 10 basic programming problems along with their solutions:

  • Hello World:

Problem: Write a program that prints “Hello, World!” to the console.

Solution (Python):

print(“Hello, World!”)

  • Sum of Two Numbers:

Problem: Write a program that inputs two numbers and prints their sum.

Solution (Java):

import java.util.Scanner;

public class SumOfTwoNumbers {

        Scanner scanner = new Scanner(System.in);

        System.out.print(“Enter first number: “);

        int num1 = scanner.nextInt();

        System.out.print(“Enter second number: “);

        int num2 = scanner.nextInt();

        int sum = num1 + num2;

  • Factorial of a Number:

Problem: Write a program to calculate the factorial of a given number.

Solution (C++):

#include <iostream>

using namespace std;

int factorial(int n) {

    if (n == 0 || n == 1)

        return 1;

        return n * factorial(n – 1);

int main() {

    int num;

    cout << “Enter a number: “;

    cin >> num;

    cout << “Factorial: ” << factorial(num) << endl;

    return 0;

  • Check Even or Odd:

Problem: Write a program that checks if a given number is even or odd.

Solution (JavaScript):

let number = 7;

if (number % 2 === 0) {

    console.log(number + ” is even”);

    console.log(number + ” is odd”);

  • Reverse a String:

Problem: Write a program to reverse a given string.

original_string = “Hello, World!”

reversed_string = original_string[::-1]

print(“Reversed String:”, reversed_string)

  • Fibonacci Series:

Problem: Generate the Fibonacci series up to a specific limit.

public class FibonacciSeries {

        int limit = 10;

        int firstTerm = 0, secondTerm = 1;

        System.out.println(“Fibonacci Series up to ” + limit + ” terms:”);

        for (int i = 1; i <= limit; ++i) {

            System.out.print(firstTerm + “, “);

            int nextTerm = firstTerm + secondTerm;

            firstTerm = secondTerm;

            secondTerm = nextTerm;

  • Check Prime Number:

Problem: Write a program to check if a given number is prime.

def is_prime(number):

    if number > 1:

        for i in range(2, int(number / 2) + 1):

            if (number % i) == 0:

                return False

        else:

            return True

        return False

if is_prime(num):

    print(num, “is a prime number.”)

    print(num, “is not a prime number.”)

  • Find Maximum Element:

Problem: Write a program to find the maximum element in an array.

int findMax(int arr[], int size) {

    int max = arr[0];

    for (int i = 1; i < size; ++i) {

        if (arr[i] > max) {

            max = arr[i];

    return max;

    int numbers[] = {5, 8, 2, 10, 3};

    int size = sizeof(numbers) / sizeof(numbers[0]);

    cout << “Maximum Element: ” << findMax(numbers, size) << endl;

  • Palindrome Check:

Problem: Write a program to check if a given string is a palindrome.

public class PalindromeCheck {

        String str = “level”;

        String reversedStr = new StringBuilder(str).reverse().toString();

        if (str.equals(reversedStr)) {

            System.out.println(str + ” is a palindrome.”);

            System.out.println(str + ” is not a palindrome.”);

  • Count Vowels and Consonants:

Problem: Write a program to count the number of vowels and consonants in a given string.

text = “Hello, World!”

vowels = “AEIOU

Benefits of Solving Basic Programming Problems

Solving basic programming problems offers numerous benefits for individuals looking to enhance their programming skills. Here are some key advantages:

Skill Development:

  • Coding Proficiency: Regular problem-solving helps improve your coding skills and fluency in programming languages.
  • Algorithmic Thinking: It fosters the development of algorithmic thinking, enabling you to devise efficient solutions to various problems.

Logical Thinking:

  • Problem Decomposition: Breaking down problems into smaller components and solving them enhances logical thinking and problem-solving abilities.
  • Pattern Recognition: Regular problem-solving helps in recognizing patterns and similarities between different problems, leading to more efficient solutions.

Learning New Concepts:

  • Exposure to Diverse Topics: Programming problems often cover a wide range of concepts, exposing you to different areas of computer science and software development.
  • New Algorithms and Data Structures: Exploring various problems introduces you to new algorithms and data structures, expanding your knowledge base.

Preparation for Interviews:

  • Technical Interviews: Many technical interviews for programming roles involve solving algorithmic and coding problems. Regular practice prepares you for such interviews and boosts your confidence.
  • Coding Challenges: Familiarity with common coding challenges often encountered in interviews is an asset.

Building a Portfolio:

  • Showcasing Skills: Solving problems allows you to build a portfolio of solutions that you can showcase to potential employers or on coding platforms.
  • GitHub Contributions: Uploading your solutions to platforms like GitHub demonstrates your coding proficiency and problem-solving ability.

Enhanced Efficiency:

  • Code Optimization: Regular practice encourages optimization, leading to more efficient and cleaner code.
  • Time Complexity Awareness: Problem-solving helps in understanding and considering time complexity, contributing to the creation of scalable solutions.

Community Engagement:

  • Online Communities: Engaging in online coding communities allows you to discuss problems, learn from others, and gain insights into alternative solutions.
  • Peer Learning: Collaborating with peers on coding challenges can provide different perspectives and foster a collaborative learning environment.

Career Advancement:

  • Competitive Edge: Building strong problem-solving skills sets you apart in a competitive job market, enhancing your employability.
  • Adaptability: A wide range of problem-solving experiences makes you more adaptable to different tasks and projects.

Personal Satisfaction:

  • Sense of Achievement: Successfully solving programming problems brings a sense of accomplishment, boosting confidence and motivation.
  • Continuous Learning: It fosters a mindset of continuous learning, crucial in a rapidly evolving field like programming.

In summary, regular practice of solving basic programming problems contributes significantly to skill development, logical thinking, and overall proficiency in the field of programming.

For Latest Tech Related Information, Join Our Official Free Telegram Group : PW Skills Telegram Group

  • What Is C In C Programming?

C Programming

Discover C programming fundamentals - from basic Syntax to advanced concepts. Learn how to write efficient and powerful code, and…

  • What is BootstrapCDN?

bootstrapcdn

Explore BootstrapCDN, a powerful tool for developers aiming to enhance website performance and user experience with Bootstrap's library distributed across…

  • What is the Program of C?

c program

There are many different ways we can use the C Program to check for a prime number. Let us read…

right adv

Related Articles

  • How to Make a Simple C Programs?
  • Is Azure DevOps Exam Easy?
  • What CSS Does in HTML?
  • What is a Div Tag in HTML?
  • What is C Language Basics?
  • What is The HTML Tag?
  • Which is The Best Course for Full Stack Development?

bottom banner

"Hello World!" in C Easy C (Basic) Max Score: 5 Success Rate: 85.68%

Playing with characters easy c (basic) max score: 5 success rate: 84.26%, sum and difference of two numbers easy c (basic) max score: 5 success rate: 94.59%, functions in c easy c (basic) max score: 10 success rate: 95.96%, pointers in c easy c (basic) max score: 10 success rate: 96.54%, conditional statements in c easy c (basic) max score: 10 success rate: 96.94%, for loop in c easy c (basic) max score: 10 success rate: 93.66%, sum of digits of a five digit number easy c (basic) max score: 15 success rate: 98.66%, bitwise operators easy c (basic) max score: 15 success rate: 94.88%, printing pattern using loops medium c (basic) max score: 30 success rate: 95.91%, cookie support is required to access hackerrank.

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

IMAGES

  1. Six Steps to Solving a Programming Problem Infographic

    problem solving programming questions

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

    problem solving programming questions

  3. Problem Solving In Programming

    problem solving programming questions

  4. Logical questions and answer in c language

    problem solving programming questions

  5. Problem Solving and Python Programming

    problem solving programming questions

  6. Problem solving (C++ Programming)

    problem solving programming questions

VIDEO

  1. Techniques of Problem solving in Programming

  2. Prefix sum array شرح || Problem solving

  3. Number Theory -GCD -LCM-Sieve of eratosthenes- Prime factorization شرح

  4. JS Problem Solving Questions 01

  5. Partial Sum شرح || Problem Solving

  6. Competitive Programming Training: Beginner to Specialist at Codeforces

COMMENTS

  1. Problems

    Boost your coding interview skills and confidence by practicing real interview questions with LeetCode. Our platform offers a range of essential problems for practice, as well as the latest questions being asked by top-tier companies.

  2. 100+ Coding Interview Questions for Programmers and ...

    Top 100 Coding Problems from Programming Job interviews. Without wasting any more of your time, here is my list of 100 frequently asked coding problems from programming job interviews. In order to get most of this list, I suggest actually solving the problem. Do it yourself, no matter whether you are stuck because that's the only way to learn.

  3. Online Coding Practice Problems & Challenges

    Medium Java puzzles. Puzzles contain a problem and a pre-defined solution. But the solution is either incomplete and your task is to complete it (Code Completion Puzzle). Or the solution is wrong and your task is to debug it (Debugging Puzzle). 118 Problems. Beginner level. Sharpen your coding skills with CodeChef.

  4. 40 Coding Challenges (SOLVED with CODE) To Kill Your Next Coding

    You may hate code challenges and coding interviews but reality is a lot of companies from Google to Amazon do care that you understand the difference between O(n log n) and O(n²), that you do understand when different data structures are appropriate, and that you can leverage these (very basic) skills to solve simple problems. Follow along and check 40 most common Coding Challenges and ...

  5. 15 Common Problem-Solving Interview Questions

    Here are a few examples of technical problem-solving questions: 1. Mini-Max Sum. This well-known challenge, which asks the interviewee to find the maximum and minimum sum among an array of given numbers, is based on a basic but important programming concept called sorting, as well as integer overflow.

  6. 22 Coding Interview Questions Every Developer Should Know

    They test a candidate's coding skills and ability to solve problems with algorithms in a programming language of their choice. Sample Question: The Efficient Janitor. The janitor of a high school is extremely efficient. By the end of each day, all of the school's waste is in plastic bags weighing between 1.01 pounds and 3.00 pounds.

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

  8. Python Practice Problems: Get Ready for Your Next Interview

    While this solution takes a literal approach to solving the Caesar cipher problem, you could also use a different approach modeled after the .translate() solution in practice problem 2. Solution 2. The second solution to this problem mimics the behavior of Python's built-in method .translate(). Instead of shifting each letter by a given ...

  9. 45 Common Coding Interview Questions

    M: Match the problem with the interviewer. P: Plan your approach and solution. I: Implement your solution. R: Review your solution. E: Evaluate your solution. To prepare for a whiteboard challenge, "practice talking through your problem-solving process ," says Archie Payne, president of CalTek Staffing, an IT and technical staffing firm.

  10. Programming tutorials, Coding problems, and Practice questions

    Functional Programming. Higher Order Functions and Decorators. Practice programming skills with tutorials and practice problems of Basic Programming, Data Structures, Algorithms, Math, Machine Learning, Python. HackerEarth is a global hub of 5M+ developers.

  11. 10 Common Coding Interview Problems [Solved]

    We just published a course on the freeCodeCamp.org YouTube channel that will teach you how to solve 10 common coding problems and improve your problem-solving skills. This course was developed Inside code. He is an experienced developer and has a good understanding of the types of coding challenges often used in programmer interviews.

  12. Practice

    Solve Problem. Easy 409K 43.49%. Platform to practice programming problems. Solve company interview questions and improve your coding intellect.

  13. Programming Problems and Competitions :: HackerRank

    When you're ready, submit your solution! Remember, you can go back and refine your code anytime.6 of 6. Check your score. Join over 11 million developers in solving code challenges on HackerRank, one of the best ways to prepare for programming interviews.

  14. Top 40 Coding Interview Questions You Should Know

    Programming questions are an integral part of an interview for the developer's position. No matter which programming language you master, familiarity with fundamental concepts of programming is something that is always expected from you.. Coding skills are always the deciding factor in any programming interview. In this coding interview questions article, we will discuss the top 40 Coding ...

  15. How to think like a programmer

    Simplest means you know the answer (or are closer to that answer). After that, simplest means this sub-problem being solved doesn't depend on others being solved. Once you solved every sub-problem, connect the dots. Connecting all your "sub-solutions" will give you the solution to the original problem. Congratulations!

  16. How to Develop Problem Solving Skills in Programming

    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.

  17. Solve Python

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

  18. Python Exercises, Practice, Challenges

    Each exercise has 10-20 Questions. The solution is provided for every question. Practice each Exercise in Online Code Editor. These Python programming exercises are suitable for all Python developers. If you are a beginner, you will have a better understanding of Python after solving these exercises. Below is the list of exercises.

  19. Basic Programming Problems

    Learn Programming - How To Code. In the world of programming, mastering the fundamentals is key to becoming a proficient developer.In this article, we will explore a variety of basic programming problems that are essential for every aspiring coder to understand. By delving into these foundational challenges, you will gain valuable insights into problem-solving techniques and build a strong ...

  20. The 10 Most Popular Coding Challenge Websites [Updated for 2021]

    The game comes with a problem description, test cases, and an editor where you can write your code in one of 20+ programming languages. Although this website is different than typical competitive programming websites such as the ones mentioned above, it is still popular amongst programmers who enjoy solving challenges and taking part in contests.

  21. 75 Basic Programming Problems and Tutorials for Practice

    Basic Programming Problems: Engaging in code challenges offers many benefits, serving as a dynamic tool to enhance problem-solving proficiency, deepen your comprehension of the programming language you work with, and acquaint yourself with diverse algorithms. If you aspire to elevate your programming skills, immersing yourself in coding is the most effective avenue.

  22. Solve C

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

  23. Problem Solving and Programming Concepts

    Find step-by-step solutions and answers to Problem Solving and Programming Concepts - 9780133001785, as well as thousands of textbooks so you can move forward with confidence. ... Problems. Page 333: Questions. Exercise 1. Exercise 2. Exercise 3. Exercise 4. Exercise 5. Exercise 6. Exercise 7. Exercise 8. Exercise 9. Exercise 10. Exercise 11 ...