Здравствуйте, друзья! Эта статья посвящена наиболее часто задаваемым вопросам на собеседованиях по программированию на технических собеседованиях. Я уверен, что если вы попрактикуетесь в этом и в вопросах программирования на собеседовании на Java 8, вы обязательно пройдете техническое собеседование. Ссылка на интервью по Java 8 здесь -



Напишите программу для балансировки скобок на Java.

import java.util.Stack;

public class BalanceBrackets {

 public static void main(String[] args) {
  String str = "[{()}]";
  boolean isBalanced = isBalanced(str);
  System.out.println("Is the string balanced? " + isBalanced);
 }

 public static boolean isBalanced(String str) {
  Stack<Character> stack = new Stack<>();

  for (char ch : str.toCharArray()) {
   if (ch == '(' || ch == '{' || ch == '[') {
    stack.push(ch);
   } else if (ch == ')' || ch == '}' || ch == ']') {
    if (stack.isEmpty()) {
     return false; // Closing bracket with no matching opening bracket
    }
    char top = stack.pop();
    // Check if the current closing bracket matches the last opening bracket
    if ((ch == ')' && top != '(') || (ch == '}' && top != '{') || (ch == ']' && top != '[')) {
     return false;
    }
   }
  }
  // If the stack is empty, all brackets are balanced
  return stack.isEmpty();
 }
Output ->  Is the string balanced : true

Напишите программу для подсчета символов строки.

public class CharacterCountInString {

 public static void main(String[] args) {
  String input = "ABACBBAA";
  String characterCountString = characterCountString(input);
  System.out.println("Character Count String: " + characterCountString);
 }

 public static String characterCountString(String input) {
  if (input == null || input.isEmpty()) {
   return input; // Return the input string as-is if it's null or empty.
  }
  StringBuilder compressed = new StringBuilder();
  char currentChar = input.charAt(0);
  int count = 1;

  for (int i = 1; i < input.length(); i++) {
   char nextChar = input.charAt(i);

   if (currentChar == nextChar) {
    // If the current character is the same as the next one, increment the count.
    count++;
   } else {
    // If a new character is encountered, append the current character and its count
    // to the result.
    compressed.append(currentChar).append(count);
    currentChar = nextChar; // Update the current character.
    count = 1; // Reset the count for the new character.
   }
  }
  // Append the last character and its count.
  compressed.append(currentChar).append(count);
  return compressed.toString();
 }
}
Output -> Character Count String: A1B1A1C1B2A2

Напишите программу, сдвигающую массив в цикле влево и вправо.

public class CycleShiftArray {

 public static void main(String[] args) {
  int shiftBy = 2; // Shift right by 2 positions

  int[] rightArr = { 1, 2, 3, 4, 5 };
  System.out.println("Input : " + Arrays.toString(rightArr));
  rightShift(rightArr, shiftBy);
  System.out.println("Right Shift Output : " + Arrays.toString(rightArr));

  int[] leftArr = { 1, 2, 3, 4, 5 };
  System.out.println("Input : " + Arrays.toString(leftArr));
  leftShift(leftArr, shiftBy);
  System.out.println("Left Shift output : " + Arrays.toString(leftArr));
 }

 public static void leftShift(int[] arr, int n) {
  int len = arr.length;
  n = n % len; 
  reverse(arr, 0, n - 1);// concentrate on this
  reverse(arr, n, len - 1);
  reverse(arr, 0, len - 1);
 }

 public static void rightShift(int[] arr, int n) {
  int len = arr.length;
  n = n % len;
  reverse(arr, 0, len - 1);// concentrate on this
  reverse(arr, 0, n - 1);
  reverse(arr, n, len - 1);
 }

 public static void reverse(int[] arr, int start, int end) {
  while (start < end) {
   int temp = arr[start];
   arr[start] = arr[end];
   arr[end] = temp;
   start++;
   end--;
  }
 }
}
Input : [1, 2, 3, 4, 5]
Right Shift Output : [4, 5, 1, 2, 3]
Input : [1, 2, 3, 4, 5]
Left Shift output : [3, 4, 5, 1, 2]

Напишите программу для поиска анаграммы.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//An anagram is a word or phrase formed by rearranging the letters of a different word or phrase,
//typically using all the original letters exactly once.
public class FindAnagram {

 public static void main(String[] args) {
  String words[] = { "rat", "tar", "cat", "tac", "act" };
  Map<String, List<String>> anagramGroups = new HashMap<>();
  for (String word : words) {
   char[] charArray = word.toCharArray();
   Arrays.sort(charArray);// sort the array
   String sortedWord = new String(charArray);
   if (!anagramGroups.containsKey(sortedWord)) {// check the word in map or not
    anagramGroups.put(sortedWord, new ArrayList<>());
   }
   anagramGroups.get(sortedWord).add(word);// Add the anagram in list
  }
  System.out.println(anagramGroups.values());

 }
}
Output -> [[rat, tar], [cat, tac, act]]

Напишите программу для поиска среднего элемента в связанном списке.

public class FindMiddleElementInLinkedList {
 private Node head;

 class Node {
  int value;
  Node next;

  public Node(int value) {
   this.value = value;
   this.next = null;
  }
 }

 public void insert(int data) {
  Node newNode = new Node(data);
  newNode.next = head;
  head = newNode;
 }

 public void print() {
  Node temp = head;
  while (temp != null) {
   System.out.print(temp.value+" ");
   temp = temp.next;
  }
 }

 public int getSize() {
  int size = 0;
  Node temp = head;
  while (temp != null) {
   size++;
   temp = temp.next;
  }
  return size;
 }

 public void findMiddleElement() {
  if (head != null) {
   int len = getSize();
   Node temp = head;
   int middleLength = len / 2;
   while (middleLength != 0) {
    temp = temp.next;
    middleLength--;
   }
   System.out.println("Middle Element Output : " + temp.value);
  }

 }

 public static void main(String[] args) {
  FindMiddleElementInLinkedList node = new FindMiddleElementInLinkedList();
  node.insert(1);
  node.insert(2);
  node.insert(3);
  node.insert(4);
  node.insert(5);
  System.out.print("Input : ");
  node.print();
  System.out.println();
  node.findMiddleElement();
 }
}
Input : 5 4 3 2 1 
Middle Element Output : 3

Напишите программу, переворачивающую связанный список.

public class ReverseLinkedList {
 private Node head;

 class Node {
  int value;
  Node next;

  public Node(int value) {
   this.value = value;
   this.next = null;
  }
 }

 public void insert(int data) {
  Node newNode = new Node(data);
  newNode.next = head;
  head = newNode;
 }

 public void print() {
  Node temp = head;
  while (temp != null) {
   System.out.print(temp.value);
   temp = temp.next;
  }
 }

 public void reverse() {
  Node curr = head;
  Node prev = null;

  while (curr != null) {
   Node next = curr.next;
   curr.next = prev;
   prev = curr;
   curr = next;
  }
  head = prev;

 }

 public static void main(String[] args) {
  ReverseLinkedList node = new ReverseLinkedList();
  node.insert(1);
  node.insert(2);
  node.insert(3);
  node.insert(4);
  node.insert(5);
  System.out.print("Input : ");
  node.print();
  node.reverse();
  System.out.println();
  System.out.print("Output : ");
  node.print();
 }
Input : 5 4 3 2 1 
Output : 1 2 3 4 5 

Напишите программу для поиска максимального порядкового номера в массиве.

public class FindSequenceNumberIsHighest {
 public static void main(String[] args) {
  String str = "11100111111001111011111110011111";
  System.out.println("Input : " + str);
  int prev = 0;
  int next = 0;
  for (int i = 0; i < str.length(); i++) {
   if (str.charAt(i) == '1') {
    prev++;
   } else if (next < prev) {
    next = prev;
   } else if (str.charAt(i) == '0') {
    prev = 0;
   }
  }
  System.out.println("Highest sequence number is : " + next);
 }
}
Input : 11100111111001111011111110011111
Highest sequence number is : 7

Напишите программу для поиска индекса шаблона в строке.

public class FindStringPatterns {
 public static void main(String[] args) {
  String str = "abcdefghi";
  String pattern = "def";
  int startIndex = str.indexOf(pattern);
  if (startIndex != -1) {
   System.out.println("Pattern starts at index: " + startIndex);
  } else {
   System.out.println("Pattern not found in the string.");
  }
  System.out.println("Find pattern by brute force algo : " + isFindPattern(str, pattern));
 }

// It is brute force algorithm to find the index
 private static int isFindPattern(String str, String pattern) {
  int ms = str.length();
  int ps = pattern.length();
  int index = 0;
  for (int i = 0; i < ms - ps + 1; i++) {
   boolean flag = true;
   for (int j = 0; j < ps && flag; j++) {
    if (str.charAt(j + i) != pattern.charAt(j)) {
     flag = false;
    }
   }
   if (flag) {
    index = i;
    break;
   }
  }
  return index;
 }
}
Pattern starts at index: 3
Find pattern by brute force algo : 3

Напишите программный алгоритм сортировки слиянием.

import java.util.Arrays;

public class MergeSort {

 public static void main(String[] args) {
  int[] arr = { 38, 27, 43, 3, 9, 82, 10 };
  System.out.println("Input  : "+ Arrays.toString(arr));
  mergeSort(arr);
  System.out.println("Merge Sorted Array: " + Arrays.toString(arr));
 }

 public static void mergeSort(int[] arr) {
  if (arr == null || arr.length <= 1) {
   return;
  }
  int mid = arr.length / 2;
  int[] left = new int[mid];
  int[] right = new int[arr.length - mid];

  // copy left arrays
  System.arraycopy(arr, 0, left, 0, mid);
  // copy right arrays
  System.arraycopy(arr, mid, right, 0, arr.length - mid);
  // Using the recursive approach
  mergeSort(left);
  mergeSort(right);

  // merge the both array in single array
  merge(arr, left, right);
 }

 private static void merge(int[] arr, int[] left, int[] right) {
  int i = 0, j = 0, k = 0;

  while (i < left.length && j < right.length) {
   if (left[i] <= right[j]) {
    arr[k++] = left[i++];
   } else {
    arr[k++] = right[j++];
   }
  }
  // Copy remaining elements from left if any
  while (i < left.length) {
   arr[k++] = left[i++];
  }
  // Copy remaining elements from right, if any
  while (j < right.length) {
   arr[k++] = right[j++];
  }
 }
}
Input  : [38, 27, 43, 3, 9, 82, 10]
Merge Sorted Array: [3, 9, 10, 27, 38, 43, 82]

Напишите программу обратной польской записи.

//Reverse Polish Notation (RPN), also known as postfix notation, is a mathematical notation in which 
// every operator follows all of its operands.
public class ReversePoliseNotation {

 public static void main(String[] args) {

  String exp[] = { "2", "3", "12", "8", "2", "/", "*", "+", "-" };
  System.out.println("Input : " + Arrays.toString(exp));
  Stack<Integer> stack = new Stack<>();

  for (int i = 0; i < exp.length; i++) {

   String v = exp[i];
   if (v.equals("+") || v.equals("-") || v.equals("*") || v.equals("/")) {

    int pop1 = stack.pop();
    int pop2 = stack.pop();
    stack.push(solve(pop2, pop1, v));
   } else {
    // Token is an operand
    stack.push(Integer.parseInt(v));
   }
  }
  System.out.println("Output: " + stack.pop());
 }

 private static Integer solve(int pop2, int pop1, String v) {
  if (v.equals("+")) {
   return pop2 + pop1;
  }
  if (v.equals("-")) {
   return pop2 - pop1;
  }
  if (v.equals("*")) {
   return pop2 * pop1;
  }
  if (v.equals("/")) {
   return pop2 / pop1;
  }
  return 0;
 }
}
Input : [2, 3, 12, 8, 2, /, *, +, -]
Output: -49

Напишите программу для двух массивов сумм для заданной цели.

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class TwoSumArray {
public static void main(String[] args) {
  int a[] = { 1, 4, 2, 6, 7, 9 };
  int target = 9;
  System.out.println("Input : " + Arrays.toString(a));
  System.out.println("Target value : " + target);
  int[] index = new int[2];
  Map<Integer, Integer> map = new HashMap<>();
  for (int i = 0; i < a.length; i++) {
   Integer temp = target - a[i];
   if (map.containsKey(temp)) {
    index[0] = map.get(temp);
    index[1] = i;
    break;
   }
   map.put(a[i], i);
  }
  System.out.println("Output Index : {" + index[0] + " " + index[1] + "}");
 }
}
Input : [1, 4, 2, 6, 7, 9]
Target value : 9
Output Index : {2 4}

Напишите программу для трех массивов сумм для заданной цели.

import java.util.Arrays;

public class ThreeSumArrays {
 public static void main(String[] args) {
  int a[] = { 1, 2, -1, -1, 3, 4, 5, 1, 8, 6 };
  int target = 9;
  System.out.println("Input : " + Arrays.toString(a));
  System.out.println("Target value : " + target);

  Arrays.sort(a);// {-1,-1,1,1,2,3,4,5,6,8}
  // two pointer approach to fix this problem
  for (int i = 0; i < a.length; i++) {
   if ((i == 0) || a[i] != a[i - 1]) {
    int j = i + 1;
    int k = a.length - 1;
    int sno = target - a[i];
    while (j < k) {
     if (a[j] + a[k] == sno) {
      System.out.println("Output : {" + a[i] + " " + a[j] + " " + a[k] + "}");
      // ignore the duplication
      while (j < k && a[j] == a[j + 1])
       j++;
      while (j < k && a[k] == a[k - 1])
       k++;
      j++;
      k--;
     } else if (a[j] + a[k] < sno) {
      j++;
     } else {
      k--;
     }
    }
   }
  }
 }
}
Input : [1, 2, -1, -1, 3, 4, 5, 1, 8, 6]
Target value : 9
Output : {-1 2 8}
Output : {-1 4 6}
Output : {1 2 6}
Output : {1 3 5}
Output : {2 3 4}

Вы можете скачать весь код в репозитории git — https://github.com/rohitk12r/top_interview_programing_question/

Спасибо, что прочитали статью. Пожалуйста, аплодируйте, делитесь и комментируйте. это побудит меня писать больше таких статей. Поделитесь своими ценными предложениями, я ценю ваши честные отзывы!!!