Posts

Showing posts from September, 2024

DSA Interview Coding Questions

1] Arrays 1] Find first and second best score Example Given an array, write a function to get first, second best scores from the array and return it in new array. Array may contain duplicates. Example myArray = { 84 , 85 , 86 , 87 , 85 , 90 , 85 , 83 , 23 , 45 , 84 , 1 , 2 , 0 } firstSecond ( myArray ) // {90, 87} Solution: import java . util . Arrays ; import java . util . Collections ; public class Exercise { public static int [] findTopTwoScores ( int [] array ) { int firstHighest = Integer . MIN_VALUE ; int secondHighest = Integer . MIN_VALUE ;   for ( int score : array ) { if ( score > firstHighest ) { secondHighest = firstHighest ; firstHighest = score ; } else if ( score > secondHighest && score < firstHighest ) { secondHighest = score ; } }   return new int []{ firstHighest , secondHighest }...

Map - DS Algo related questions

The Map data structure in Java is widely used in various scenarios and is a common topic in technical interviews. Here are some examples of how Map can be used in different programs or interview questions, along with Java and Java 8 code snippets. 1. Counting Frequency of Elements Problem: Given an array of integers, count the frequency of each element. Example: import java.util.HashMap; import java.util.Map; public class FrequencyCounter { public static void main (String[] args) { int [] arr = { 1 , 2 , 2 , 3 , 3 , 3 , 4 , 4 , 4 , 4 }; Map<Integer, Integer> frequencyMap = new HashMap <>(); for ( int num : arr) { frequencyMap.put(num, frequencyMap.getOrDefault(num, 0 ) + 1 ); } System.out.println(frequencyMap); } } Output: {1=1, 2=2, 3=3, 4=4} 2. Finding First Non-Repeated Character in a String Problem: Given a string, find the first non-repeated character. Example: import java.util.LinkedHashMa...

List - DS Algo related questions

In programming, the List data structure is widely used in various scenarios, and interview questions often revolve around its practical applications. Here are some examples of programs where a List is used: 1. Basic Operations on Lists Problem: Implement a program to reverse a list Usage: The list is traversed, and its elements are reordered. Core Java: import java.util.*; public class ReverseList { public static List<Integer> reverseList (List<Integer> list) { Collections.reverse(list); return list; } } Java 8: import java.util.*; import java.util.stream.*; public class ReverseList { public static List<Integer> reverseList (List<Integer> list) { return IntStream.rangeClosed( 1 , list.size()) .mapToObj(i -> list.get(list.size() - i)) .collect(Collectors.toList()); } } Problem: Write a program to remove duplicates from a list. Usage: Lists are used ...