Back to Blog

Programming Interview Questions & Answers
Coding

117 Programming Interview Questions & Answers [2024 Prep Guide]

34 minute read | May 19, 2023
Kindra Cooper

Written by:
Kindra Cooper

Ready to launch your career?

There’s never been a better time to launch a career in software engineering. With exceptionally strong prospects, the US Bureau of Labor Statistics projects a 22% job growth for software developers, analysts, and testers by 2030. 

But before you land a job as a software engineer, you’ll have to ace the programming interview. Programming interviews test your knowledge of computer science fundamentals and assess your knowledge of the foundations of programming logic and problem-solving skills. Knowledge of data structures and algorithms is essential, as well as familiarity with the programming language of your choice. 

In this post, we’ll give you answers to the 117 most common interview questions. This includes basic programming questions, along with more advanced technical questions regarding strings, linked lists, and binary trees. Finally, we’ll give you tips on how to format your resume and portfolio. 

Basic Programming Interview Questions

What Is Computer Programming?

Computer programming is how engineers tell a computer, application, or software program what to do. At the most basic level, programming is the process of writing a set of instructions. 

Explain How Programming Works.

Once the code is written, the code is then compiled or interpreted, a process that converts source code into machine code, which is the only programming language a computer can understand. The computer then executes the code to perform the desired task. 

Explain the Workings of a Compiler.

A compiler translates (compiles) source code written in a programming language (i.e. Java, C++, Python) into a set of machine-language instructions that can be understood by a computer. 

Explain Debugging.

Debugging is the process of detecting, correcting, and removing errors in source code. It starts with identifying a problem (i.e. finding a software defect), isolating the source of the problem in the code, and then correcting the problem or creating a workaround. 

What Is an Algorithm?

An algorithm is a set of instructions to be followed in a problem-solving operation.

Explain the Types of Errors That Are Likely To Occur While Running and Executing a Program.

When the compiler finds something wrong with the program, there are three kinds of errors:

Syntax Error

A syntax error occurs when the code does not follow the syntax rules of the programming language. These are the easiest errors to find and correct. 

Runtime Error

This is an error that takes place while running a program, causing the program to crash or hang. 

Logic Error

This is an error in the way that a program works (i.e. the program runs but not as expected). It is a type of runtime error that may produce the wrong output or cause a program to crash. Logic errors are the hardest to spot because they can be caused by a variety of factors. 

How Does a Syntax Error Occur?

Syntax errors can occur when you misspell a statement, or you’re missing a punctuation mark. Another possibility is using a variable before it has been declared. Missing brackets (i.e. opening a bracket but not closing it) is another common cause. 

How Does a Runtime Error Occur?

Coding:

Runtime errors can occur for a variety of reasons, such as a memory leak (when a program consumes too much RAM without releasing it), programming errors, an incomplete installation, or a corrupt registry.

How Does a Logical Error Occur?

Various programming mistakes can cause logic errors. Examples include: assigning a value to the wrong variable, incorrectly using logical operators or Boolean operators, using incorrect program design, or multiplying two numbers instead of adding them together. 

What Do You Mean by a Flowchart?

A flowchart is a diagram that depicts a process, system, workflow, or computer algorithm. Essentially, they represent a step-by-step approach to solving a problem. 

What Does It Mean To “Maintain and Update the Program?”

Software maintenance is the process of modifying and updating software that has already been published. This is done to correct faults, improve performance, and keep the program secure from cyber attacks

Define the Term “Variables.”

Variables are like containers where information can be maintained and referenced. Each variable is labeled with a symbolic name that tells you what information it contains. The sole purpose of variables is to label and store data in memory. 

Get To Know Other Software Engineering Students

Alyssa Menes

Alyssa Menes

Software Engineer at Progyny

Read Story

Rafael Alvarado

Rafael Alvarado

IT Support Engineer at Amazon

Read Story

Bryce Dunn

Bryce Dunn

Associate Software Engineer at Egen

Read Story

What Do You Mean by Reserved Words?

A reserved word is a word in a programming language that has a fixed meaning and cannot be redefined by the programmer. It may look like a “normal” word, but it cannot be used as an identifier, such as the name of a variable, function, file name, command, or label. For example, “print” is a reserved word because it is a function in many languages to show text on the screen. 

Explain the Concept of Loops.

A loop is a sequence of instructions that are repeated until a certain condition is reached. In a loop structure, the loop asks a question (i.e. has X variable reached a value of 5?). If the answer is no, an action is executed. The question is asked again and again until no further action is required. A loop prevents programmers from having to write the same line of code over and over. 

Tell Us About the Various Types of Loops.

There are various types of loops that can be used in high-level programming languages, such as C, C++, and C#.

How Do You Use FOR….NEXT Loop?

The FOR…NEXT loop works by running the loop a specified number of times. For example, if you ask a computer to add the integers 1-10, it would add the first two numbers, followed by a third, a fourth, and so on, until it reaches the 10th iteration.  

How Do You Use WHILE….WEND Loop?

In a While…Wend loop, if the condition is true, all the statements are executed until the Wend keyword is encountered. If the condition is false, the loop is exited and the control jumps to the very next statement after the Wend keyword. 

How Do You Use the Nested Loop?

You can nest loops by putting one loop within another. The first pass of the outer loop triggers the inner loop, which executes to completion. The second pass of the outer loop triggers the inner loop again. This process repeats until the outer loop finishes. 

What Do You Mean by Documentation?

Documentation is the explanation of how to use and operate a piece of software. This includes information on requirements, architecture/design, technical specifications as well as instruction manuals for the end-user, system administrator, and support staff. Documentation includes requirements documents, user documentation, system documentation, process documentation, and product documentation. 

What Do We Call the Binary Form of a Target Language?

The binary form of a target language is also called binary code.

Explain Constants.

Constants are data values that stay constant every time a program is executed. Literal constants are actual values fixed into the source code. “Named” constants are constants that have been associated with an identifier, where the constant is known by its name instead of the literal constant. 

What Are the Two Types of Constants?

Numeric Constants

A numeric constant consists of numerals, an optional leading sign, and an optional decimal point. Examples of valid numerical constants include 2.3, -4, and 6. 

String Constants

A string constant consists of a sequence of characters enclosed in double-quotes. It may consist of any combination of digits, letters, escaped sequences, and spaces. 

Explain Numeric Constants.

There are two types of numeric constants: integer constants and real constants. Integer constants do not have a decimal point. They can be written using decimal numbers (base 10), octal numbers (base 8), or hexadecimal numbers (Base 16) that represent an integral value. A real constant is a constant that has a decimal point. They can be written in either fractional or exponential form. 

Explain String Constants.

A string constant—also known as a string literal—is an arbitrary sequence of characters enclosed in double quotation marks. 

What Do You Mean by Operators?

Operators are the backbone of every software application. An operator is a symbol that represents an action or process. This symbol tells the compiler to perform specific arithmetic or relational operations, such as adding or subtracting two numbers, to produce a final result. 

Define an Array.

An array is a series of “boxes” or memory locations that hold a single item of data. However, each box shares the same name. All data in an array must be the same data type. 

What Do You Mean by Subroutine?

A subroutine designates a section of code using a specific name. Each subroutine performs a particular function—it is essentially a small program, so it can contain any of the sequence, selection, and iteration constructs. Using subroutines makes the code more readable and reusable because it breaks the code into smaller sections. 

What Is the Use of Arithmetic Operators?

Arithmetic operators are symbols that represent arithmetic operations for values or variables to compute an output. Examples include addition (+), subtraction (-), multiplication (x or *) and division (÷ or /). 

What Is the Use of Relational Operators?

A relational operator is a programming language construct or operator that tests or defines a relationship between two entities. These include numerical equality (e.g., 5 = 5) and inequalities (e.g., 4 ≥ 3). They allow computers to compare numeric and character values to determine if one is greater than, less than, or equal to another. 

What Do You Mean by Low-Level Programming Language?

Low-level programming languages can be converted to machine code without a compiler. The resulting code runs directly on the processor. There are two types of low-level programming languages: machine language (a series of numbers written in binary) and assembly language, which is one step closer to high-level language than machine language.   

What Do You Mean by High-Level Programming Language?

High-level programming languages are human-readable programming languages that are used to write software programs and scripts. They must be converted into machine language using a compiler in order for a computer to understand the instructions, and are also closer to natural language. Examples include Python, Java, Ruby, and C#.

Define Machine Code.

Machine code refers to any low-level programming language consisting of machine language instructions. It is composed of hexadecimal or binary numbers and appears as a long sequence of ones and zeros. Computer programs are rarely written in machine code because doing so is tedious and error-prone. However, writing in machine code may be done for low-level debugging, program patching, and when disassembling the assembly language. 

Write a Code in 32-Bit x86 Machine Code To Calculate the Nth Fibonacci Number.

Source: GitHub

Can You List Some Programming Languages?

There are over 700 programming languages, each with different use cases and platforms. Here is a list of the top 10 most common programming languages and their most common uses. 

  1. Python (AI and machine learning)
  2. Javascript (rich interactive web development)
  3. Java (enterprise application development)
  4. R (data analysis)
  5. C/C++ (operating systems and system tools)
  6. Golang (server-side programming)
  7. C# (application and web development using .NET)
  8. PHP (web development)
  9. SQL (data management)
  10. Swift (mobile app development on iOS)

Explain Reliability.

Reliability is the measure of how consistently a computer-related component (software, hardware, or a network) performs according to its specifications. Software reliability is the probability that a software program will function without failure for a specified period of time, which in turn affects system reliability. The reliability of a programming system is determined by the number of errors to be expected but also its behavior in error situations. Reliability is also an important criterion for evaluating programming languages (i.e. the extent to which the code is crash-proof).

What Do You Mean by Modeling Language?

Unified Modeling Language (UML) is a general-purpose language that provides a standardized method for visualizing the design of a system. UML diagrams are a common visual language intended to be understood by developers and non-technical professionals alike. 

What Is the Use Case for Software Testing?

Software testing is the process of checking whether a piece of software meets the requirements and is error-free. The purpose of testing is to prevent bugs, improve performance, and identify missing requirements. 

Explain the Term “Beta Version.”

A beta version is the pre-released version of a software program that is distributed to a large group of users, who try using the software under real-world conditions. 

Why Do We Use Logical Operators?

A logical operator helps computers make decisions based on certain conditions. 

What Is the Use Case of Assignment Operators?

Assignment operators are used in C/C++ to assign value to a variable using the “=” symbol. The left operand is a variable and the right operand is a value. The value on the right side must be of the same data type as the variable on the left. Otherwise, the compiler will raise an error. 

What Do You Mean by Analyzing a Program?

Program analysis is the process of evaluating the behavior of a computer program to determine if it is operating correctly. Program analysis focuses on two major areas: program optimization and program correctness. The former focuses on improving the program’s performance, while the latter ensures the program performs as intended. 

How Many Steps Does an Algorithm Perform?

When we determine how long an algorithm takes to execute, we count the number of steps. Algorithms should be composed of a finite number of steps and they should complete their execution in a finite amount of time. In other words, every algorithm must reach some operation that tells it to stop. 

How Do You Define Division by Zero?

A mathematical division by zero is an illegal operation in computer programming and results in an error message (not defined). This is because zero represents a null or non-existent value. When an integer is divided by zero, this causes an interrupt on the CPU. 

What Does It Mean To Implement a Program?

Implementation is the interaction of elements in programming languages. Program implementation is the realization of technical specifications or algorithms as a program, software component, or other computer systems through computer programming and deployment. 

Explain Numeric Variables.

A numeric variable is a variable with a numerical value. For example, the height of a cliff measured in feet is a numerical value. Numeric variables may be continuous  (they can assume an infinite number of real values within a given interval) or discrete (they can only assume a finite number of real values in a given interval). 

Explain String Variables.

String variables are variables that contain characters besides numbers, such as letters and symbols. 

What Do You Mean by Commands?

A command is a unique word or phrase used to perform a specific operation. For example, “print” is a command used to display text on the screen.  

How Do You Define the Execution of a Program?

Execution is the process by which a computer reads and acts on a set of instructions needed to run a software program, script, or command. Execution occurs when the source code has been converted into machine language by a compiler, which then yields an output based on a sequence of operations. 

How Do You Design an Algorithm To Count the Occurrence of a Word in an Article?

Use the count() function in Python. 

  • First, split the string by spaces and store it in a list.
  • Use count() to find the count of that word in the list. 

How Do You Implement a Blocking Queue in Java?

Java provides several BlockingQueue implementations such as LinkedBlockingQueue, ArrayBlockingQueue, PriorityBlockingQueue, and SynchronousQueue. Their uses are as follows:

LinkedBlockingQueue: an optionally bounded blocking queue based on linked nodes 

ArrayBlockingQueue: a bounded blocking queue backed by an array

PriorityBlockingQueue: an unbounded blocking queue that uses the same ordering rules as PriorityQueue and supplies blocking retrieval operations

SynchronousQueue: a special blocking queue with no internal capacity

String Programming Interview Questions 

What Is a String?

A string is a data type—such as an integer or floating-point unit—used to represent text rather than numbers. 

How Do You Reverse a String?

In Python, strings can be reversed using slicing. To reverse a string, simply create a slice that starts with the length of the string and ends at index 0. 

stringname[stringlength::-1] # method 1 

To reverse a string without specifying the length of the string:

stringname[::-1] # method2

The slice statement means start at string length, end at position 0, move with the step -1 (one step backward). 

What Is a Palindrome String?

A palindrome string occurs when the reverse of a string is the same as the original string.

Can You Get Matching Characters in a String? If So, Then How?

  • Initialize a counter variable with 0. 
  • Iterate over the first string from the starting character to the ending character. 
  • If the character extracted from the first string is found in the second string, then increment the value of the counter by 1.
  • The final answer will be count/2 as the duplicates are not being considered.
  • Output the value of the counter.

How Do You Check if a String Is a Palindrome or Not? Write a Code for the Same.

The simplest solution is to reverse the string and compare it to the original. If they are the same, the given string is a palindrome. 

C++

C++

Java

programming interview questions: Java

Python

python

Source: Techie Delight

How Do You Remove Any Given Character From a String?

Python: You can remove a character from a Python string using replace() or translate(). Both methods replace a character or string with a given value. 

Java: The replace function can be used to remove a character from a Java string. You can also use the deleteCharAt or substring method. 

How Do You Print All Permutations of String—Both Iterative and Recursive?

A permutation (AKA an “arrangement number” or “order) is an arrangement of all or part of a set of objects, with regard to the order of the arrangement. 

Code answer:

Programming Interview Questions

Source: Codegrepper

Write a Function To Find Out the Longest Palindrome in a Given String.

  1. Maintain a variable ‘ maxLength = 1 ‘ (for storing LPS length) and ‘ start =0 ‘ (for storing starting index of LPS).
  2. If the idea is very simple, we will traverse through the entire string with i=0 to i<(length of the string).
    • While traversing, initialize the ‘low‘ and ‘high‘ pointers such that low= i-1 and high= i+1.
    • Keep incrementing ‘high’ until str[high]==str[i] .
    • Similarly keep decrementing ‘low’ until str[low]==str[i].
    • Finally, keep incrementing ‘high’ and decrementing ‘low’ until str[low]==str[high].
    • Calculate length=high-low-1, if length > maxLength then maxLength = length and start = low+1.
  3. Print the LPS and return maxLength.

[Source]

What Is the Best Way To Find the First Non-Repeated Character of a Given String?

A character is non-repeating if its frequency in the string is a unit. To find such characters, find the frequency of all characters in the string and check which character has a unit frequency. This can be done using a hash_map, which will map each character to its respective frequency. You can simultaneously update the frequency of any character you come across in constant time (note that hash_map can only handle up to 256 characters at a time). Read the string again and the first character which has a frequency as a unit is the answer. 

Algorithm: 

  1. Make a hash_map that will map the character to their respective frequencies.
  2. Traverse the given string using a pointer.
  3. Increase the count of the current characters in the hash_map.
  4. Now traverse the string again and check whether the current character hasfrequency=1.
  5. If the frequency >1, continue the traversal.
  6. Else break the loop and print the current character as the answer.

[Source]

How Do You Count the Occurrence of a Given Character in a String?

You can count the occurrence of a value in strings using the count() function. In Python, you can also use the following:

collections.Counter
findall()
defaultdict
pandas.value_counts()
Lambda functions

for Loop

How Do You Check if Two Strings Are Anagrams?

Method 1: Use sorting

  • Sort both strings
  • Compare the sorted strings

Method 2: Count characters

This method is best for when the number of possible characters in both strings is small (256 or less).

  • Create count arrays of size 256 for both strings. Initialize all values in count arrays as 0.
  • Iterate through every character of both strings and count the characters in the corresponding count arrays.
  • Compare count arrays. If both count arrays are the same, then return true.

How Do You Convert Numeric String to Int in Java?

To convert a string into an int, use the Integer.parselnt() method:

programming interview questions: How Do You Convert Numeric String to Int in Java?

Source: Javapoint

Java String Programming Interview Questions

In Java, What Is the Difference Between String, StringBuilder, and StringBuffer?

A string represents a sequence of characters. In Java, strings are objects. Java has provided the StringBuffer and StringBuilder classes that can be used for string manipulation. 

StringBufferStringBuilder
StringBuffer is synchronized (thread-safe). It means two threads can’t call the methods of StringBuffer simultaneously. StringBuilder is non-synchronized (not thread-safe). It means two threads can call the methods of StringBuilder simultaneously.
Less efficientMore efficient
Introduced in Java 1.0Introduced in Java 1.5

Can You Split a String in Java? If So, How?

The string#split() method breaks a given string around matches of the given regular expression. It then returns a char array. Say you have a string “004-034556.” When you split the string, the first string will contain the characters before ‘-’ and the second string will contain the characters after ‘-’.

String string = "004-034556"; 
String[] parts = string.split("-"); 
String part1 = parts[0]; // 004 
String part2 = parts[1]; // 034556

Why Is a String Final in Java?

Strings in Java are immutable for the sake of security, synchronization and concurrency, easy reuse without replication, caching, and class loading. 

Why Is a Char Array Preferred Over a String for Storing Passwords?

Since strings are immutable, there is no way to change the contents of a string once it has been created, other than by creating a new string. Storing passwords in a character array mitigates the risk that the password may be stolen or manipulated. 

Programming Questions on Arrays

Given Two Arrays—1,2, 3,4, 5 and 2,3, 1,0, 5—Can You Find Which Number Is Not Present in the Second Array?

Examples: 

Input : a[] = {1, 2, 3, 4, 5, 10};
    b[] = {2, 3, 1, 0, 5};
Output : 4 10    

4 and 10 are present in first array, but not in second array.

Input : a[] = {4, 3, 5, 9, 11};
        b[] = {4, 9, 3, 11, 10};
Output : 5 

Method 1: Naive Approach

Use two loops and check which elements are not present in the second array. 

Method 2: Hashing

In this method, we store all elements of the second array in a hash table (unordered set). Check all elements of the first array and print all those elements which are not present in the hash table.

How Do You Find the Second-Highest Number in an Integer Array?

The easiest way is to sort the array in descending order and return the second element which is not equal to the largest element from the sorted array. 

The most efficient way, however, is to find the second largest element in a single traversal. Below is the complete algorithm for doing this: 

1) Initialize the first as 0(i.e, index of arr[0] element
2) Start traversing the array from array[1],
   a) If the current element in array say arr[i] is greater
      than first. Then update first and second as,
      second = first
      first = arr[i]
   b) If the current element is in between first and second,
      then update second to store the value of current variable as
      second = arr[i]
3) Return the value stored in second.

[Source]

How Do You Find All of the Pairs in an Array of Integers Whose Sum Is Equal to the Given Number?

Traverse each element and check if there’s another number in the array which can be added to it to yield sum. 

Can You Remove Duplicate Elements From an Array in Java? If So, How?

Yes. There are two ways to do this: using a temporary array or a separate index. 

Using temporary array:

public class RemoveDuplicateInArrayExample{  
public static int removeDuplicateElements(int arr[], int n){  
        if (n==0 || n==1){  
            return n;  
        }  
        int[] temp = new int[n];  
        int j = 0;  
        for (int i=0; i<n-1; i++){  
            if (arr[i] != arr[i+1]){  
                temp[j++] = arr[i];  
            }  
         }  
        temp[j++] = arr[n-1];     
        // Changing original array  
        for (int i=0; i<j; i++){  
            arr[i] = temp[i];  
        }  
        return j;  
    }  
       
    public static void main (String[] args) {  
        int arr[] = {10,20,20,30,30,40,50,50};  
        int length = arr.length;  
        length = removeDuplicateElements(arr, length);  
        //printing array elements  
        for (int i=0; i<length; i++)  
           System.out.print(arr[i]+" ");  
    }  
}  

Using separate index: 

public class RemoveDuplicateInArrayExample2{  
    public static int removeDuplicateElements(int arr[], int n){  
        if (n==0 || n==1){  
            return n;  
        }    
        int j = 0;//for next element  
        for (int i=0; i < n-1; i++){  
            if (arr[i] != arr[i+1]){  
                arr[j++] = arr[i];  
            }  
        }  
        arr[j++] = arr[n-1];  
        return j;  
    }  
       
    public static void main (String[] args) {  
        int arr[] = {10,20,20,30,30,40,50,50};  
        int length = arr.length;  
        length = removeDuplicateElements(arr, length);  
        //printing array elements  
        for (int i=0; i<length; i++)  
           System.out.print(arr[i]+" ");  
    }  
}  

What Is the Best Way To Find the Largest and Smallest Number in an Array?

Traverse the array iteratively and keep track of the smallest and largest element until the end of the array.

Algorithm: 

  1. Input the array elements.
  2. Initialize small = large = arr[0]
  3. Repeat from i = 2 to n
  4. if(arr[i] > large)
  5. large = arr[i]
  6. if(arr[i] < small)
  7. small = arr[i]
  8. Print small and large.

How Do You Find the Top Two Maximum Numbers in an Array?

  1. Take two variables; let’s call them first and second and mark them as -∞.
  2. Iterate through the array and for each element (let’s call it current). 
  3. Compare it with the first and if the first is less, assign the first value to the second and assign the current to the first.
  4. If the above step is not true then the current element might be a candidate for the second highest element, so check if current>second. If yes then assign it to second.

Code:

programming interview questions: How Do You Find the Top Two Maximum Numbers in an Array?

Source: Tutorial Horizon

In an Array Where the Numbers 1–100 Are Stored, and One Number Is Missing, How Do You Find It?

The length of the array is n-1. So the sum of all n elements, (i.e the sum of numbers from 1 to n) can be calculated using the formula n*(n+1)/2. Now, find the sum of all the elements in the array and subtract it from the sum of the first n natural numbers, it will be the value of the missing element.

Algorithm: 

  1. Calculate the sum of the first n natural numbers as sumtotal= n*(n+1)/2.
  2. Create a variable sum to store the sum of array elements.
  3. Traverse the array from start to end.
  4. Update the value of sum as sum = sum + array[i].
  5. Print the missing number as the sum total.

[Source]

LinkedList Programming Interview Questions

How To Get the Length of a Linked List?

Write a function to count the number of nodes in a singly linked list using the iterative or recursive algorithm. Watch this video for a full walkthrough:

YouTube video player for kX_OJsOcK8Q

Iterative:

1. Initialize count as 0 

2. Initialize a node pointer, current = head.

3. Do following while current is not NULL

     a) current = current -> next

     b) count++;

4. Return count

Recursive:

int getCount(head)

1. If the head is NULL, return 0.

2. Else return 1 + getCount(head->next)

How Do You Search for a Specific Value in a Linked List?

1. Iterate the linked list using a loop.

2. If any node has the given key-value, return 1.

3. If the program execution comes out of the loop (the given key is not present in the linked list), return -1.

Search Found        => return 1.

Search Not Found => return -1.

Watch this video for a full walkthrough:

YouTube video player for lWEBpaVPoJA

How Do You Find the Middle Element of a Linked List in a Single Pass?

For an even number of nodes, the solution is obvious. The middle element occurs when there is an equal number of nodes on either side. If there are even nodes, there would be two middle nodes, so you need to print the second middle element. Traverse the whole linked list and count the number of nodes. Now traverse the list again till count/2 and return the node at count/2. Watch this video for a full walkthrough.

How Do You Find the 3rd Element From the List in a Single Pass?

  • Use two pointers: pointer-1 and pointer-2
Make pointer-1 points to the third node in a single linked list.
pointer-1 = node1->next->next; // point to 3rd nd node1-->node2-->node3-->node4---> ...... -->node-last ^ | pointer-1
  • Now set pointer-2 points to first-node
pointer-2 = node1; // point to 1st nd node1-->node2-->node3-->node4---> ...... -->node-last ^ ^ | | pointer-2 pointer-1
  • Now, travel in linked list in a loop till pointer-1 points to last node, in loop also update pointer-2 (every time to next node of itself)
while (pointer-1->next!=NULL){// points to last node pointer-1 = pointer-1 -> next; pointer-2 = pointer-2 -> next; } When loop ends pointer-1 points to last-node, pointer-2 points to third last node1-->node2-->........ ->node-l3-->node-l2-->node-last ^ ^ | | pointer-2 pointer-1

It works in O(n) times, where n is the number of nodes in the linked-list.

[Source]

What’s One Way To Detect a Loop in a Singly Linked List?

Traverse the list one by one and keep putting the node addresses in a Hash Table. At any point, if NULL is reached then return false, and if the next of the current nodes point to any of the previously stored nodes in Hash then return true.

[Source]

How Do You Find the Start of the Loop?

You can use Floyd’s loop detection algorithm to solve this problem. Below are steps to find the first node of the loop.

1. If a loop is found, initialize a slow pointer to the head, and let the fast pointer be at its position. 

2. Move both slow and fast pointers one node at a time. 

3. The point at which they meet is the start of the loop.

Can You Reverse a Singly Linked List?

Reversing a linked list simply means reassigning all the next properties on every node (changing the links between nodes).

How Do You Implement the Process of Reversing a Linked List?

  1. Initialize three-pointers prev as NULL, curr as head, and next as NULL.
  2. Iterate through the linked list. In loop, do the following:
    // Before changing next of current,
    // store next node
    next = curr->next
    // Now change next of current
    // This is where actual reversing happens
    curr->next = prev
    // Move prev and curr one step forward
    prev = curr
    curr = next

[Source]

What’s the Difference Between a Linked List and an Array Data Structure?

Both of these data structures can be used to store linear data of a similar type, but an array consumes contiguous memory locations allocated at compile time (at the time of declaration of an array). For a linked list, memory is assigned as and when data is added to it (i.e. at runtime).

Binary Tree Programming Interview Questions

How Do You Find the Depth of a Binary Tree?

The maximum depth of a binary tree is the number of nodes or edges from the root down to the furthest leaf node. In other words, it is synonymous with height. If the target node has no other nodes connected to it, the depth of that node is 0. 

How Do You Print Out All Leaf Nodes of a Binary Tree?

The nodes should be printed in the order they appear, from left to right. 

  1. Check if the given node is null. If null, then return from the function.
  2. Check if it is a leaf node. If the node is a leaf node, then print its data.
  3. If the node is not a leaf node then check if the left and right children of the node exist. If yes, then call the function for the left and right child of the node recursively.

In Java, How Do You Check Whether a Tree Is a Binary Search Tree or Not?

Performing an inorder traversal for the binary tree will track previous nodes in inorder traversal. If the previous node is less than the current node, then it is a binary search tree.

In Java, How Do You Check Whether a Tree Is a Binary Search Tree or Not?

Source: Java2blog

In Java, Can You Check Whether or Not a Tree Is Balanced? If So, Then How?

A well-formed binary tree is said to be “height-balanced” if (1) it is empty, or (2) its left and right children are height-balanced and the height of the left tree is within 1 of the height of the right tree.

In Java, Can You Check Whether or Not a Tree Is Balanced? If So, Then How?

Source: Stack Overflow

Explain Binary Search Tree Implementation.

A binary search tree is a variation of the rooted binary tree in which the nodes are arranged in an order. The value of the left node must be smaller than the parent node, and the value of the right node must be greater than the parent node. This rule is applied recursively to the left and right subtrees of the root. Also, the left and right subtree must also be a binary search tree. There cannot be any duplicate nodes. 

How Do You Perform Preorder Traversal in a Given Binary Tree?

Trees can be traversed in multiple ways: 

Depth-first traversal: 

(a) Inorder (Left, Root, Right) : 4 2 5 1 3 

(b) Preorder (Root, Left, Right) : 1 2 4 5 3 

(c) Postorder (Left, Right, Root) : 4 5 2 3 1

Breadth-First or Level Order Traversal: 1 2 3 4 5 

Inorder traversal: 

Algorithm Inorder(tree)

1. Traverse the left subtree, i.e., call Inorder(left-subtree)

2. Visit the root.

3. Traverse the right subtree, i.e., call Inorder(right-subtree)

Preorder traversal: 

Algorithm Preorder(tree)

1. Visit the root.

2. Traverse the left subtree, i.e., call Preorder(left-subtree)

3. Traverse the right subtree, i.e., call Preorder(right-subtree)

How Do You Traverse a Binary Tree in Preorder Without Recursion?

1. Create an empty stack nodeStack and push the root node to stack. 

2. Do the following while nodeStack is not empty: 

  • Pop an item from the stack and print it. 
  • Push the right child of a popped item to stack. 
  • Push the left child of a popped item to stack.

The right child is pushed before the left child to make sure that the left subtree is processed first.

How Do You Print All Nodes of a Binary Tree Using Inorder Traversal but Without Recursion?

  1. Initialize the variable “current” node as the root 
  2. While the “current” node is not NULL
  3. If the current node lacks a left child
  4. Print the information in the current node
  5. Visit the right child, current = current->right
  6. Else
  7. In the current left subtree, find the rightmost node or find the node whose right child == current.
  8. If the node’s right child == current
  9. Update the node’s right child as NULL
  10. Print the information in current
  11. Visit the right child, current = current->right
  12. Else
  13. Set the current variable as the right child of that rightmost node found; and 
  14. Visit the left child, current = current->left

[Source]

Explain the Postorder Traversal Algorithm Implementation.

The postorder traversal is one of the traversing techniques used for visiting the node in the tree. It follows the principle LRN (Left-right-node). Postorder traversal is used to get the postfix expression of a tree.

The following steps are used to perform the postorder traversal:

  • Traverse the left subtree by calling the postorder function recursively.
  • Traverse the right subtree by calling the postorder function recursively.
  • Access the data part of the current node.

How Do You Traverse a Binary Tree in Postorder Traversal Without Recursion?

Move down to the leftmost node using the left pointer. While moving down, push root and root’s right child to stack. Once you reach the leftmost node, print it if it doesn’t have a right child. If it has a right child, then change the root so that the right child is processed before. 

The algorithm goes as follows:

1. Create an empty stack

2. Do the following while the root is not NULL:

    a) Push root’s right child and then root to stack.

    b) Set root as root’s left child.

3. Pop an item from the stack and set it as root.

    a) If the popped item has a right child and the right child is at the top of the stack, then remove the right child from the stack, push the root back and set root as root’s right child.

    b) Else print root’s data and set root as NULL.

4. Repeat steps 2 and 3 while the stack is not empty.

How Do You Print All Leaves of a Binary Search Tree?

You can use recursion to print all the leaves of a binary tree in Java. Since the tree is a recursive data structure, you can apply the same algorithm to the left and right subtree. You can print all leaf nodes by traversing the tree, checking each node to find if their left and right child nodes are null, and then printing that node. 

How Do You Count the Number of Leaf Nodes in a Given Binary Tree?

1) If the node is NULL then return 0.

2) Else If left and right child nodes are NULL return 1.

3) Else recursively calculate leaf count of the tree using the formula below.

Leaf count of a tree = Leaf count of left subtree + Leaf count of right subtree

How Do You Perform a Binary Search in a Given Array?

  • Begin with an interval covering the whole array.
  • If the value of the search key is less than the item in the middle of the interval, narrow the interval to the lower half.
  • Otherwise, narrow it to the upper half.
  • Repeatedly check until the value is found or the interval is empty.

Programming Questions on Searching and Sorting

Write a Program To Sort Numbers in Place Using Quicksort.

Quicksort is a divide-and-conquer algorithm. It picks an element as a pivot and partitions the given array around the chosen pivot. 

  1. An array is divided into subarrays by selecting a pivot element (element selected from the array). While dividing the array, the pivot element should be positioned so that elements less than the pivot are kept on the left side, and elements greater than the pivot are on the right.
  2. The left and right subarrays are also divided using the same approach. This process continues until each subarray contains a single element.
  3. At this point, elements are already sorted. Finally, elements are combined to form a sorted array.

[Source]

Pseudocode for recursive quicksort function:

programming interview questions: Pseudocode for recursive quicksort function:

Source: Geeks For Geeks

How Do You Sort Java Objects Using a Comparator?

A comparator provides an ordering for collections of objects that don’t have a natural ordering. This class’s implementer needs to override the abstract method compare() defined in java.util.Comparator, which compares its two arguments for order. The value returned by the compare() method decides the position of the first object relative to the second object.

  • If compare() returns a negative integer, the first argument is less than the second.
  • If compare() returns a zero, the first argument is equal to the second.
  • If compare() returns a positive integer, the first argument is greater than the second.

Programming Questions on Numbers

How Do You Reverse a Number?

Input:  num

(1) Initialize rev_num = 0

(2) Loop while num > 0

     (a) Multiply rev_num by 10 and add remainder of num  

          divide by 10 to rev_num

               rev_num = rev_num*10 + num%10;

     (b) Divide num by 10

(3) Return rev_num

How Do You Check Whether or Not a Number Is a Power of Two?

A simple method for this is to take the log of the number on base 2. If you get an integer, then the number is the power of 2.

What Is the Best Way To Check Whether a Number Is a Palindrome or Not?

A simple method is to first reverse digits of n, then compare the reverse of n with n. If both are the same, then return true; if not, return false.

n = num; 
rev = 0; 
while (num > 0) 
{ 
dig = num % 10; 
rev = rev * 10 + dig; 
num = num / 10; 
}
If n == rev then num is a palindrome:
cout << "Number " << (n == rev ? "IS" : "IS NOT") << " a palindrome" << endl;

How Do You Find All Prime Numbers Up to a Given Number?

Write a program using two nested for loops. 

  • The first for loop is used to loop between the numbers provided by the user. For example, 2 to 10.
  • A variable flag is set to 0.
  • The second for loop is used to loop between 2 to the number that is stored in i.
  • Inside the second loop, the value of i is divided by each number from 2 to a value one less than i (i – 1).
  • While dividing, if any number remainder results in 0, that number is not a prime number. So the variable flag is set to 1.
  • Finally, all the numbers that have a flag 0 (not divisible by other numbers) are printed.

Javascript program

programming interview questions: Javascript program

Source: Programiz

Compute the First Five Fibonacci Numbers.

Write a function int fib(int n) that returns Fn. For example, if n = 0, then fib() should return 0. If n = 1, then it should return 1. For n > 1, it should return Fn-1 + Fn-2.

See this video for a complete walkthrough:

YouTube video player for uCt82T5mW8I

Write a Function To Compute the Nth Fibonacci Number, Both Iterative and Recursive.

Iterative:

programming interview questions: Write a Function To Compute the Nth Fibonacci Number, Both Iterative and Recursive.

Source: Techie Delight

Output:

F(n) = 21

[Source]

Recursion:

programming interview questions: Recursion

Output

12th Element of the Fibonacci Series: 144

How Do You Check if a Number Is Binary?

  1. Check if the number is less than or equal to 1. If it is then, print false.
  2. Else, if the number is greater than 1, check if any digit is a 1 or 0.
  3. If any digit is greater than 1 then print false; else, print true.

How Do You Reverse an Integer in Java?

programming interview questions: How Do You Reverse an Integer in Java?

Source: Programiz

Output

Reversed Number: 4321

How Do You Find the Sum of Digits of a Number Using Recursion?

Let the number be 12355. 

Step 1: 12345 % 10 which is equal-too 5 + ( send 12345/10 to next step ) 

Step 2: 1234 % 10 which is equal-too 4 + ( send 1234/10 to next step ) 

Step 3: 123 % 10 which is equal-too 3 + ( send 123/10 to next step ) 

Step 4: 12 % 10 which is equal-too 2 + ( send 12/10 to next step ) 

Step 5: 1 % 10 which is equal-too 1 + ( send 1/10 to next step ) 

Step 6: 0 algorithm stops 

How Do You Swap Two Numbers Without Using a Temp Variable?

Get a sum in one of the two given numbers. The numbers can then be swapped using the sum and subtraction from the sum. 

// Java Program to swap two numbers without

// using temporary variable

import java.io.*;

class Geeks {

public static void main(String a[])

{
		int x = 10;
		int y = 5;
		x = x + y;
		y = x - y;
		x = x - y;
		System.out.println("After swapping:"
						+ " x = " + x + ", y = " + y);
	}
}

Output

After Swapping: x =5, y=10

[Source]

In Java, How Do You Find the Largest of Three Integers?

Use the ternary operator, which evaluates a Boolean expression and assigns a value based on the result. You can use it in place of the if-else statement. The syntax of the ternary operator is as follows:

variable_name = (expression) ? value if true:value if false  

If the above expression returns true the value before the colon is assigned to the variable variable_name, else the value after the colon is assigned to the variable.

import java.util.Scanner;  
public class LargestNumberExample1  
{  
public static void main(String[] args)   
{  
int a, b, c, largest, temp;  
//object of the Scanner class  
Scanner sc = new Scanner(System.in);  
//reading input from the user  
System.out.println("Enter the first number:");  
a = sc.nextInt();  
System.out.println("Enter the second number:");  
b = sc.nextInt();  
System.out.println("Enter the third number:");  
c = sc.nextInt();  
//comparing a and b and storing the largest number in a temp variable  
temp=a>b?a:b;  
//comparing the temp variable with c and storing the result in the variable  
largest=c>temp?c:temp;  
//prints the largest number  
System.out.println("The largest number is: "+largest);  
}  
}  

Output

Enter the first number:

23

Enter the second number:

11

Enter the third number:

67

Largest Number is: 67

Can You Add Two Integers Without Using an Arithmetic Operator? If So, Then How?

Write a program to add two numbers without using the +, ++, -, or — operator. Use any loop, such as for, while, or do-while. 

programming interview questions: Can You Add Two Integers Without Using an Arithmetic Operator? If So, Then How?

Explain the bubble sort algorithm.

Bubble sort is the simplest sorting algorithm that works by comparing adjacent elements and repeatedly swapping them if they are in the wrong order. 

General Programming Interview Questions 

Introduce Yourself.

Keep your answer short (about one minute) and focused on the job you’re applying for. A good format is: “I’m an XX with X years of experience doing X for XX.” If you have different kinds of experience on your resume (for example, if you’ve switched careers), then you should start with an overview statement that encapsulates your journey and purpose. If you have a lot of experience, focus on your last two or three roles. If you’ve only been working for one year or less, summarize your experience with relevant projects and skills. End with your future goals, and how the role you’re applying for fits into those goals. 

What Do You Know About Programming?

Programming is the process of writing step-by-step instructions for a computer to execute. These instructions are written in a specific syntactic form called a programming language, which is a type of language computers can understand. Source code needs to be converted into machine language so that machines can understand the instructions and execute the program. The process of converting source code into machine language is known as compiling. 

Why Are You Interested in Programming?

Talk about your motivations for entering the field. Briefly describe how you learned programming—especially if you’re a self-taught coder, bootcamp graduate, or have switched careers. Learning how to code the “unconventional” way shows you are committed to this field. Finally, discuss what you love about the day-to-day aspect of programming. If there is a particular aspect of programming you enjoy, mention it. 

What Is the Most Challenging Task You Have Encountered on Your Learning Journey?

Tell them about a time when you faced conflict at work, went above and beyond to complete a project on deadline, or solved an unforeseen problem. 

Programming Interview FAQs

How Do You Prepare for a Programming Interview?

Study the programming language used by the company, along with their tools of choice. Practice a few coding challenges each day. Practice sample technical interview questions using online resources like LeetCode, HackerEarth, and HackerRank. “Cracking the Coding Interview,” a book by software engineer Gayle Laakmann McDowell, is recommended reading for developers searching for their next role. 

Are Programming Interviews Hard?

Programming interviews are generally difficult because you’re expected to code a solution under time constraints, while also explaining your thought process to the interviewer. Interview questions are designed to be difficult because the cost of hiring a bad engineer is very high. 

However, remember that interviewers do not expect you to know the answer to every question in an interview. They are also interested in your ability to ask the right questions, think outside of the box, and work within given constraints. They will also evaluate how clean your code is or how long it takes you to come up with a solution. 

Which Language Is Considered the Best for Programming?

Python is the main coding language for 80% of developers. This is because Python has extensive libraries and frameworks that support a variety of applications, including AI, data science, and machine learning processes. Python is also easy for beginners to learn because of its readability and user-friendly data structures. Javascript is a top programming language for front-end developers. 

How Long Does It Take To Learn Programming?

Generally, it takes 3-6 months to learn the basics of coding, but it depends on your learning method. For example, self-study takes about 6-12 months to master basic coding concepts, while most coding bootcamps run for 3-6 months. A college degree takes four years to complete. 

Can I Become an Expert in Programming Within 6 Months?

While you can certainly master the basics, it is not a realistic timeframe to become a programming expert in six months. This is because there is such a wide range of programming languages, each with its own application and use cases. Your best bet is to choose a programming language to specialize in, such as Python or C, and learn as many code concepts as you can in the next six months. 

Programmers need to have a range of skills, including the ability to adopt new technologies, solve problems, and notice little details. These are skills you will continuously develop the more you practice programming.

Related Read: 64 Coding Interview Questions + Answers

Since you’re here…
No one wakes up knowing how to code – they learn how to code. Tens of thousands of students have successfully learned with our courses, like our Software Engineering Bootcamp. If you’re a total newbie, our Software Engineering Career Track Prep Course will be a perfect fit. Let’s do this!

About Kindra Cooper

Kindra Cooper is a content writer at Springboard. She has worked as a journalist and content marketer in the US and Indonesia, covering everything from business and architecture to politics and the arts.