Vijay Singh Khatri | 16 Feb, 2022

50+ Best Programming Interview Questions and Answers in 2024


Big firms like Amazon, Google, and Microsoft are always on the hunt to add programming and software development talent to join their rolls. So, in order to bag a lucrative opportunity at big names like the aforementioned, one needs to accumulate as much knowledge as possible.

In order to ease your endeavour, we have compiled a list of top programming interview questions that anyone aiming for programming interview questions must know.

Top Programming Interview Questions and Answers

So, without any further ado, here we go:

Question: Please explain what you understand by computer programming.

Answer: Also known as coding or programming, computer programming is the process of encoding an algorithm into a notation, typically a computer program, by means of some programming language so that it can be executed by a computer.

Each programming language contains a set of instructions for the computer to execute a set of tasks. Programming is a complex process that includes designing an algorithm, coding the same in a programming language, debugging a program, maintaining, and updating the code.

Question: Can you enumerate and explain the various types of errors that can occur during the execution of a computer program?

Answer: Three types of errors can occur during the execution of a computer program. These are:

  • Logical errors – This occurs in the scenario of a computer program implementing the wrong logic. As there is no report generated for these types of programming errors, they are the most difficult ones to deal with.
  • Runtime errors – Occurs when the program contains an illegal operation. For example, dividing a number by 0. These are the only errors that are displayed instantly during the program execution. Upon the occurrence of a runtime error, the program execution is stopped and a diagnostic message is displayed.
  • Syntax errors – Occurs when one or more grammatical rules of the programming language being used is violated. Such errors are detected during compile time.

Question: Please explain an algorithm. What are some of its important features?

Answer: An algorithm can be defined as a set of finite steps that when followed helps in accomplishing a particular task. Important features of an algorithm are clarity, efficiency, and finiteness.

Question: What do you understand by maintaining and updating a computer program?

Answer: The maintenance and updating process of a computer program starts post its successful installation. While program maintenance is the continuous process of monitoring the computer program for bugs and errors, updating the computer program means making it better with minor and major changes over time.

Question: Please provide a brief explanation on variables.

Answer: Variables are used for storing the input of a program as well as the computational results during program execution. These are actually named memory locations. The value stored in a variable can change during the program execution.

Question: Every programming language has reserved words. What are they? Give some examples.

Answer: Reserved words, also known as keywords, are the words that have predefined meanings in a particular programming language. These reserved words can’t be used or redefined for serving other purposes. Following are some examples of reserved words:

  • C – break, case, char, default, else, float, if, and int
  • Java – abstract, boolean, catch, class, const, double, enum, finally, implements, instanceof, throws, transient, and volatile
  • Python – and, assert, continue, def, del, global, not, lambda, raise, and yield

Question: What do you understand by loops? Briefly explain the various types of loops.

Answer: A loop is a structure in programming that can repeat a defined set of statements for a set number of times or until a particular condition is satisfied. There are three important types of loops:

  • FOR…NEXT Loop – This is the most effective loop when you know beforehand the total number of times the loop is to be repeated
  • WHILE…WEND Loop – It keeps on repeating a particular action until the concerned condition becomes false. This loop is particularly useful when the total number of repetitions is unknown.
  • Nested Loop – When a loop is used inside a loop then it is termed as a nested loop

Question: Please explain program documentation. Why is it important?

Answer: Program documentation is the written description of the algorithm(s), coding method, design, testing, and proper use of a particular computer program. It is valuable for those who use the program on a day-to-day basis and also for the programmer(s) who are meant to correct, modify, and update the computer program.

Reliable documentation is a must for an earnest programmer. The availability of thorough documentation helps not only in keeping track of the various aspects of a computer application but also helps in improving the overall quality of the same. The main focus of program documentation is development, maintenance, and knowledge transfer to other developers.

Question: What are constants? Explain their types.

Answer: A constant is a programming entity whose value can’t be changed or modified during program execution. Constants are of two main types:

  • Numeric constants – Includes integers, single-precision, and double-precision numbers. For example, 22, 24, -898, 4.5, and 73.45
  • String constants – Includes a sequence of alphanumeric characters enclosed in double quotation marks. The maximum length of a string constant is 255 characters. For example, “Shimla,” “I Love You,” and “Orange Is the New Black”

Question: Please explain the operators.

Answer: Operators are used for performing certain operations on data in a computer program. These are represented by symbols. For example, / represent mathematical division while * represents multiplication. There are 4 main types of operators:

  • Arithmetic – Used for carrying out mathematical operations
  • Assignment – Used for storing computational results, strings, and values in variables
  • Logical – Used for allowing a computer program to make a decision based on multiple conditions. In other words, logical operators allow combining simple conditions to form more complex conditions
  • Relational – Used for defining or testing some kind of relation between two entities. These operators evaluate to either true or false and produce a non-zero value

Question: Could you explain arrays?

Answer: An array is a programming structure that is a collection of several data values of the same type. In terms of memory, an array is a group of contiguous memory locations storing data of the same type.

Question: What do you understand by a subroutine?

Answer: A self-contained set of statements usable from anywhere in a computer program is known as a subroutine. Once the subroutine successfully performs its intended task it returns the control to the section of the program called the subroutine.

Question: Explain low-level and high-level programming languages. Also, give some examples.

Answer: Any programming language that offers no generalization from the computer’s instruction set architecture is a low-level programming language. Assembly language and machine language are two typical examples of low-level programming languages.

A programming language that offers high generalization from the computer’s instruction set architecture is termed a high-level programming language. Typically, a high-level programming language has elements resembling natural language to make program development easier.

Another definition of a high-level programming language is one that is independent of the underlying processor of the system in which it is running. C++, Java, and Python are some of the most popular high-level programming languages.

Question: What do you understand by machine code?

Answer: Machine code is a low-level programming language. Unlike high-level programming languages that come with a compiler to transform high-level code into machine code for execution, a microprocessor directly processes machine code without doing such a transformation.

Question: Do you know about modeling languages? Give some examples.

Answer: Any artificial language usable for expressing information or knowledge or systems in an arrangement determined by a reliable set of rules is called a modeling language.

The same set of rules is also used for interpreting the meaning of the components of a modeling language structure. Following are some examples of modeling languages:

  • Business Process Modeling Notation
  • Extended Enterprise Modeling Language
  • Flowchart
  • Jackson Structured Programming
  • Systems Modeling Language
  • Unified Modeling Language

Question: Please explain software testing. Why do we need it?

Answer: Like programming, software testing is an important aspect of any software development life cycle model, whether it be the traditional waterfall model or the modern Rapid Application Development (RAD) model.

Under the process of software testing, the software is tested in certain conditions to check for the quality of the same. Another important motive for testing a computer program is to assess whether it succeeds in delivering a good user experience or not. Some other reasons include:

  • Checking for improvements
  • Ensure proper/intended working
  • Meeting user requirements

Question: What do you mean by “beta version” of a computer program?

Answer: The beat version of a computer program or software is a release of the same that isn’t yet ready for public release and is meant to be modified after user feedback received from beta testing.

Question: Can you explain the top-down design approach?

Answer: The top-down design approach is a methodology adopted for analyzing software. Instead of tackling a problem as a whole, it is first divided into a number of sub-problems. Each of them is then solved individually. The solutions are then combined to get the best solution.

Question: What do you understand by program implementation?

Answer: Post the successful completion of software testing of a computer program, it needs to be installed and put into operation on the targeted computer(s). This process of installing and setting up the computer program to be used by end-users is termed as program implementation.

Question: Please explain program execution.

Answer: Program execution is the process of carrying out instructions innate to the program by the computer. Before execution, the computer program is required to be loaded into the memory (RAM) of the computer.

Question: What is a compiler?

Answer: A compiler is a computer program that translates written code in one programming language into another language. Typically, compiler refers to a program that translates source code pertaining to a high-level programming language to a lower-level programming language for creating an executable program.

Answer: During the testing of a computer program, a number of issues are discovered. These are called errors and bugs. Debugging is the process of correcting them. In other words, debugging is the process of correcting the failures discovered in the implemented code.

Answer: Any typical computer program contains hundreds to thousands of LOC. Adding comments is a way to simplify the experience of examining or finding something within the code easier for others.

Question: Can you enumerate some coding best practices?

Answer: Following are some coding best practices to make programming efficient:

  • Abide by the DRY principle
  • Follow some easy-to-remember naming convention
  • Keep the code as straightforward as possible
  • Limit the length of a line of code
  • Use comments frequently
  • Use consistent indentation
  • Whenever and wherever possible, avoid deep nesting

Question: Can you please explain the DRY principle?

Answer: DRY stands for Don’t Repeat Yourself. It is a software development principle that aims at reducing the repetition of software patterns. For achieving this, either the repetitive software patterns need to be replaced with abstractions or data normalization must be used.

Question: What are the violations of the DRY principle called? Where are they found typically?

Answer: They are termed WET solutions. Although WET typically stands for Write Everything Twice, in some cases it might also mean We Enjoy Typing or Waste Everyone’s Time. WET solutions are usually adopted in multi-tiered architectures.

Question: Please explain bubble sorting?

Answer: Bubble sorting is a simple sorting algorithm in which adjacent elements in a data structure, such as an array, are continuously compared until we get the right order. The compared elements are swapped only if they are in the wrong order.

Bubble sort allows the smaller values to “bubble” to the top of the list, and hence the name. It is also called a sinking sort because of the bigger values “sink” to the bottom. See how does Bubble sort in C works.

Question: Please explain data structures.

Answer: A data structure is a particular way of organizing and manipulating data. It allows efficient access as well as modification of data.

A data structure can also be defined as a collection of data, the functions applicable to them, and the relationships among them. Arrays, linked lists, heaps, graphs, and stacks are some examples of data structures.

Question: What are some of the areas that leverage data structures?

Answer: Data structures are required about everywhere where data is involved. However, some notable examples are:

  • Artificial intelligence
  • Compiler design
  • Database management
  • Graphics
  • Numerical analysis
  • Operating systems
  • Statistical analysis

Answer: Sorting is the process of arranging the elements of an array in either ascending or descending order. Some of the popular sorting techniques are:

Answer: The binary search is best applied to a list in which all the elements are already sorted. The binary search starts with searching in the middle of the list.

If the middle element is not the targeted element then it proceeds to search either the lower half or the upper half of the list. The process keeps on repeating until the desired element is found.

Question: How will you reference all elements in a one-dimensional array?

Answer: We need to use an indexed loop for referencing all elements in a one-dimension array. The counter starts from 0 to the number equal to 1 less than the array size. Hence, all elements are referenced in sequence by employing the loop counter as the array subscript.

Question: What do you understand by LIFO and FIFO?

Answer: LIFO and FIFO are two of the most popular forms of accessing, retrieving, and storing data. LIFO stands for Last In First Out. This means that in this approach the latest stored data is retrieved the first. This approach is followed in a stack.

FIFO stands for First In First Out and is the opposite approach of LIFO. Here, the data that is stored the oldest is the one to be retrieved first. FIFO approach is followed in a queue.

Question: Can you explain multi-dimensional array?

Answer: A conventional array has only one index. A multi-dimensional array is one that has multiple indexes. It is used where single-dimensional indexing is insufficient.

Question: Please explain a graph.

Answer: A type of data structure that has a set of ordered pairs is called a graph. These ordered pairs are also called arcs or edges. They are used for connecting nodes, which is where data is stored to and retrieved from.

Question: What is the difference between a linear and a non-linear data structure?

Answer: In a linear data structure, data elements are placed adjacent to each other. Arrays, linked lists, queues, and stacks are some examples of linear data structure.

In a non-linear data structure, it is possible for data elements to be connected to more than two data elements. Examples of the non-linear data structure are graphs and trees.

Question: Please explain an AVL tree.

Answer: A binary search tree that is always partially balanced is called an AVL tree. It is the first-ever data structure to be designed in such a way. The balance is the difference between the heights of the subtrees from the root.

Question: Why do we use Huffman’s algorithm?

Answer: For extending binary trees that have minimum weighted path length from given weights, we use Huffman’s algorithm. It uses a table containing the total number of times for each data element.

Answer: Fibonacci search is a type of search algorithm that applies to a sorted array. It uses the divide-and-conquer approach for greatly reducing the time required for reaching the target element.

Question: How does the recursive algorithm works?

Answer: The recursive algorithm divides a problem into smaller, easy-to-manage sub-problems. The output gained from one recursion after processing one sub-problem becomes input for the subsequent recursive process.

Question: What is a recursive function?

Answer: A function that calls itself is called a recursive function. It is based on a terminating condition and uses a stack. The phenomenon is called recursion.

Question: Please explain how does dynamic memory allocation help in managing data?

Answer: Dynamic memory allocation helps in storing simple structured data types. Moreover, it helps in combining separately allocated structure blocks for forming composite structures that can be expanded or contracted as required.

Question: What is the difference between NULL and VOID?

Answer: While NULL represents a value, VOID represents data type identifier. A variable with a NULL value represents an empty value. Pointers that have no initial size are identified using VOID.

Question: Please explain how variable declaration affects memory allocation.

Answer: A particular data type is defined with a variable declaration. The total amount of memory to be allocated depends on the data type a declared variable belongs to.

Question: Please explain data abstraction.

Answer: Data abstraction helps in breaking down a complex data problem into easily-manageable sub-problems. Following data abstraction, first data objects and operations to be performed on the same are specified. How the data objects will be stored in the memory becomes a secondary task.

Question: What the code to check a String is palindrome or not? 

Answer:

#include <string.h>
int main()
{
   char a[1000];  
   int i,n,b=0;
   printf("Enter  the string : ");
   gets(a);
   n=strlen(a);
   for(i=0;i<n/2;i++)  
   {
  if(s[i]==a[n-i-1])
  b++;
  }
  if(b==i)
      printf("string is palindrome");
   else
       printf("string is not palindrome");
   return 0;
}

Output:

Enter the string: madam
String is palindrome

Question: Write a method that will remove any given character from a String?

Answer: 

public class RemoveChar {  
   public static void main(String[] args) {  
             String str = "How are you";
             System.out.println(charRemoveAt(str, 7));  
          }  
          public static String charRemoveAt(String str, int p) {  
             return str.substring(0, p) + str.substring(p + 1);  
          }  

Result:

How are you

Question: Print all permutation of String Recursive way?

Answer: 

Recursive way:

public class ABC {
   // Function to print all the permutations of str
   static void printPerm(String str, String ans)
   {
       // If string is empty
       if (str.length() == 0) {
           System.out.print(ans + " ");
           return;
       }
       for (int i = 0; i < str.length(); i++) {
           // ith character of str
           char ch = str.charAt(i);
           // Rest of the string after excluding 
           // the ith character
           String ros = str.substring(0, i) + 
                        str.substring(i + 1);
           // Recurvise call
           printPerm(ros, ans + ch);
       }
   }
   // Driver code
   public static void main(String[] args)
   {
       String s = "abb";
       printPermutn(s, "");
   }
}

Output:

abb abb bab bba bab bba

Question: Write a function to find out the longest palindrome in a given string?

Answer: 

public class Demo {
public static void main(String[] args) {
    Demo lp = new Demo();
    String pal = lp.LongPalindrome("bananas");
       System.out.println("" + pal);    
    pal = lp.LongPalindrome("abaradab121");
       System.out.println("" + pal);
}
public String LongPalindrome(String s) {
    // Validations
    if (s.isEmpty()) {
        return "Please enter a String";
    }
    if (s.length() == 1) {
        return s;
    }
    // Validations end
    // Start with one char (starting) as a longest palindrome
    String longest = s.substring(0, 1);
    for (int i = 0; i < s.length(); i = i+1) {
        // get longest palindrome for odd length (center is i)
        String tmp = checkForEquality(s, i, i);
        if (tmp.length() > longest.length()) {
            longest = tmp;
        }
        // get longest palindrome for even length (center is i, i+1)
        tmp = checkForEquality(s, i, i + 1);
        if (tmp.length() > longest.length()) {
            longest = tmp;
        }
    }
    return longest;
}
public String checkForEquality(String s, int begin, int end) {
    while (begin >= 0 && end <= s.length() - 1 && s.charAt(begin) == s.charAt(end)) {
        begin--;
        end++;
    }
return s.substring(begin + 1, end);
}
}

Question: How to convert numeric String to int in Java?

Answer: 

public class StringToInteger { public static void main(String args[])
{
String integer = "237";
int number = new Integer(integer);
System.out.println("Integer created from String in Java : " + number);  number = Integer.parseInt(integer);
System.out.println("String to int using parseInt() : " + number);  number = Integer.valueOf(integer);
System.out.println("String to int Conversion example using valueOf : " + number);
String negative = "-237";
System.out.println("Converting negative String to int in Java");
System.out.println("String to Integer Constructor Example :" + new Integer(negative));
System.out.println("String to Integer parseInt Example : " + Integer.parseInt(negative));
System.out.println("String Integer valueOf Example : " + Integer.valueOf(negative));
}
 }

Result Output:

Integer created from String in Java: 237 
String to int using parseInt() : 237
String to int Conversion example using valueOf : 237
Converting negative String to int in Java
String to Integer Constructor Example : -237
String to Integer parseInt Example : -237
String Integer valueOf Example : -237

Question: Why String is final in Java?

Answer: There are two main reasons why string is final in Java to ensure the performance and security.  If strings are mutable then it can be easily attacked as strings are used in database URL and network connections. If strings are immutable then there are no synchronization issues as it will make the string thread-safe.

Question: How to remove duplicate elements from the array in Java?

Answer: 

import java.io.*;
import java.util.*;  
class DupElements
{
   static int duplicate(int[] arr, int n)
   {
       // Find array sum and subtract sum 
       // first n-1 natural numbers from it 
       // to find the result.
       int sum = 0;
       for (int i = 0; i < n; i++)
           sum += arr[i];
       return sum - (((n - 1) * n) / 2); 
   }
   // Driver code
   public static void main(String args[]) 
   {
       int[] arr = { 9, 8, 2, 6, 11, 8, 18, 3, 4, 5 };
       int n = arr.length;
       System.out.println(duplicate(arr, n));
   }
}

Output:

8

Question: How to check if a tree is balanced or not in Java? 

Answer: 

class NodeTree {
   int data;
   Node left, right;
   Node(int d)
   {
       data = d;
       left = right = null;
   }
}
class BinaryTree {
   NodeTree root;
   /* Returns true if binary tree with root as root is height-balanced */
   boolean isBalanced(NodeTree node)
   {
       int lh; /* for height of left subtree */
       int rh; /* for height of right subtree */
       /* If tree is empty then return true */
       if (node == null)
           return true;
       /* Get the height of left and right sub trees */
       lh = height(node.left);
       rh = height(node.right);  
       if (Math.abs(lh - rh) <= 1
           && isBalanced(node.left)
           && isBalanced(node.right))
           return true;
       /* If we reach here then tree is not height-balanced */
       return false;
   }    
   int height(Node node)
   {
       /* base case tree is empty */
       if (node == null)
           return 0; 
       /* If tree is not empty then height = 1 + max of left
        height and right heights */
       return 1 + Math.max(height(node.left), height(node.right));
   }  
   public static void main(String args[])
   {
       BinaryTree tree = new BinaryTree();
       tree.root = new Node(1);
       tree.root.left = new Node(2);
       tree.root.right = new Node(3);
       tree.root.left.left = new Node(4);
       tree.root.left.right = new Node(5);
       tree.root.left.left.left = new Node(8);
       if (tree.isBalanced(tree.root))
           System.out.println("Tree is balanced");
       else
           System.out.println("Tree is not balanced");
   }
}

Output:

Tree is not balanaced

Question: Write a program to find all prime numbers up to a given number?

Answer: 

public class ABC {
   public static void main(String[] args)
   {
       Scanner sc = new Scanner(System.in);
       // Declare the variables
       int a, b, i, j, flag;
       System.out.printf("Enter lower bound of the interval: ");
       a = sc.nextInt(); // Take input
       System.out.printf("\nEnter upper bound of the interval: ");
       b = sc.nextInt(); // Take input 
       // Print display message
       System.out.printf("\nPrime numbers between %d and %d are: ", a, b); 
       for (i = a; i <= b; i++) {
           if (i == 1 || i == 0)
               continue;
           flag = 1;
           for (j = 2; j <= i / 2; ++j) {
               if (i % j == 0) {
                   flag = 0;
                   break;
               }
           }
           if (flag == 1)
               System.out.println(i);
       }
   }
}

Output:

Enter lower bound of the interval: 2
Enter upper bound of the interval: 10
Prime numbers between 2 and 10 are:  3 5 7 

Question: Write a program to find out if two rectangles R1 and R2 are overlapping?

Answer: 

class OverlapRect {  
  static class RectPoint { 
       int x, y;
   } 
// Returns true if two rectangles (a1, b1) and (a2, b2) overlap
static  boolean doOverlap(Point a1, Point b1, Point a2, Point b2) {
       // If one rectangle is on left side of other 
       if (a1.x > b2.x || a2.x > b1.x) {
           return false;
       }  
       // If one rectangle is above other 
       if (a1.y < b2.y || a2.y < b1.y) {
           return false;
       }
       return true;
   }
   public static void main(String[] args) {
       Point a1 = new Point(),
   b1 = new Point(),
       a2 = new Point(),
b2 = new Point();
       a1.x=0;a1.y=10; b1.x=10;b1.y=0;
       a2.x=5;a2.y=5; b2.x=15;b2.y=0;
       if (doOverlap(a1, b1, a2, b2)) {
           System.out.println("Rectangles Overlap");
       } else {
           System.out.println("Rectangles Don't Overlap");
       }
   }
}

Output:

Rectangles Overlap

Question: Write a program for word-wrap which should work on any screen size?

Answer:

public class WordWrap
{
   final int MAX = Integer.MAX_VALUE;      
   // A utility function to print the solution
   int printSolution (int p[], int n)
   {
       int k;
       if (p[n] == 1)
       k = 1;
       else
       k = printSolution (p, p[n]-1) + 1;
       System.out.println("Line number" + " " + k + ": " + 
       "From word no." +" "+ p[n] + " " + "to" + " " + n);
       return k;
   }  
   void solveWordWrap (int l[], int n, int M)
   {
       int extras[][] = new int[n+1][n+1];
       int lc[][]= new int[n+1][n+1];  
       int c[] = new int[n+1];
       int p[] =new int[n+1]; 
       for (int i = 1; i <= n; i++)
       {
           extras[i][i] = M - l[i-1];
           for (int j = i+1; j <= n; j++)
           extras[i][j] = extras[i][j-1] - l[j-1] - 1;
       }
       for (int i = 1; i <= n; i++)
       {
           for (int j = i; j <= n; j++)
           {
               if (extras[i][j] < 0)
                   lc[i][j] = MAX;
               else if (j == n && extras[i][j] >= 0)
                   lc[i][j] = 0;
               else
                   lc[i][j] = extras[i][j]*extras[i][j];
           }
       }      
       c[0] = 0;
       for (int j = 1; j <= n; j++)
       {
           c[j] = MAX;
           for (int i = 1; i <= j; i++)
           {
               if (c[i-1] != MAX && lc[i][j] != MAX && 
                  (c[i-1] + lc[i][j] < c[j]))
               {
                   c[j] = c[i-1] + lc[i][j];
                   p[j] = i;
               }
           }
       }    
       printSolution(p, n);
   }  
   public static void main(String args[])
   {
       WordWrap w = new WordWrap();
       int l[] = {3, 2, 2, 5};
       int n = l.length;
       int M = 6;
       w.solveWordWrap (l, n, M);
   }
}

Output:
Line number 1: From word no. 1 to 1
Line number 2: From word no. 2 to 3
Line number 3: From word no. 4 to 4

Question: Write a program to implement a blocking queue in Java?

Answer: 

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class ProducerConsumer {
public static void main(String[] args) {    
    BlockingQueue<Message> queue = new ArrayBlockingQueue<>(10);
    Producer producer = new Producer(queue);    
    Consumer consumer = new Consumer(queue);
    new Thread(producer).start();
   new Thread(consumer).start();
    System.out.println("Producer and Consumer started");
}
}

Output:

Producer and Consumer started
Produced 0
Produced 1
Produced 2
Produced 3
Produced 4
Consumed 0
Produced 5
Consumed 1
Produced 6
Produced 7
Consumed 2
Produced 8

Question: How to check if two String are Anagram?

Answer: 

import java.io.*;
import java.util.Arrays;
import java.util.Collections;
class Anagram {
   static boolean areAnagram(char[] str1, char[] str2)
   {
       // Get lenghts of both strings
       int n1 = str1.length;
       int n2 = str2.length;
       // If length of both strings is not same,
       // then they cannot be anagram
       if (n1 != n2)
       return false;
       // Sort both strings
       Arrays.sort(str1);
       Arrays.sort(str2);  
       // Compare sorted strings
       for (int i = 0; i < n1; i++)
           if (str1[i] != str2[i])
               return false;  
        return true;
   }  
   public static void main(String args[])
   {
       char str1[] = { 'w', 'e', 's', 't' };
       char str2[] = { 't', 't', 'e', 'w' };
       if (areAnagram(str1, str2))
           System.out.println("The two strings are"
                              + " anagram of each other");
       else
           System.out.println("The two strings are not"
                              + " anagram of each other");
   }
}

Output:

The two strings are not anagram of each other.

Question: Given two arrays, 1,2,3,4,5 and 2,3,1,0,5 find which number is not present in the second array?

Answer: 

class ABC 
{
   static void findMissing(int a[], int b[], 
                           int n, int m)
   {
       for (int i = 0; i < n; i++)
       {
           int j;
           for (j = 0; j < m; j++)
               if (a[i] == b[j])
                   break;
           if (j == m)
               System.out.print(a[i] + " ");
       }
   }
   // Driver Code
   public static void main(String[] args)
   {
       int a[] = { 1, 2, 3, 4, 5 };
       int b[] = { 2, 5, 3, 1, 0 };
       int n = a.length;
       int m = b.length;          
       findMissing(a, b, n, m);
   }
}

Output:

4, 0

Question: How to find the largest and smallest number in an array?

Answer: 

public class FindNumber {
    public static void main(String[] args) {
            int numbers[] = new int[]{45,23,87,13,63};
            int smallest = numbers[0];
            int biggest = numbers[0];         
            for(int i=1; i< numbers.length; i++)
            {
                    if(numbers[i] > biggest)
                               biggest = numbers[i];
                    else if (numbers[i] < smallest)
                               smallest = numbers[i];                 
            }           
            System.out.println("Largest Number is : " + biggest);
            System.out.println("Smallest Number is : " + smallest);
    }
}

Output:

Largest Number is : 87
Smallest Number is : 13

Question: How to find the top two maximum number in an array?

Answer: 

public class MaxNumbers {
   public void TwoMaxNumbers(int[] nums){
       int maxOne = 0;
       int maxTwo = 0;
       for(int n:nums){
           if(maxOne < n){
               maxTwo = maxOne;
               maxOne =n;
           } else if(maxTwo < n){
               maxTwo = n;
           }
       }
       System.out.println("First Max Number: "+maxOne);
       System.out.println("Second Max Number: "+maxTwo);
   }
   public static void main(String a[]){
       int num[] = {5,34,12, 18,50 ,23};
       TwoMaxNumbers tmn = new TwoMaxNumbers();
       tmn.printTwoMaxNumbers(num);
   }
}

Output:

First Max Number: 50
Second Max Number: 34

Conclusion

Wanna prepare more? This highly rated udemy course has helped thousands of interview candidates so must be useful to you as well: Break Away: Programming And Coding Interviews.

That completes our list of the programming interview questions that every aspiring programmer must know, and these questions will help you to crack the technical interviews. If you find some other problems at the time of the interview which are not listed here, please comment, and we will add those in the given list. All the best!

People are also reading:

By Vijay Singh Khatri

With 5+ years of experience across various tech stacks such as C, C++, PHP, Python, SQL, Angular, and AWS, Vijay has a bachelor's degree in computer science and a specialty in SEO and helps a lot of ed-tech giants with their organic marketing. Also, he persists in gaining knowledge of content marketing and SEO tools. He has worked with various analytics tools for over eight years.

View all post by the author

Subscribe to our Newsletter for Articles, News, & Jobs.

I accept the Terms and Conditions.

Disclosure: Hackr.io is supported by its audience. When you purchase through links on our site, we may earn an affiliate commission.

In this article

Learn More

Please login to leave comments