Tree Data Structure Questions for Coding Interviews Preparation

Hello folks, I have been sharing a lot of resources about programming job interviews like the books, courses, and some interview questions on the software design and data structures like an array, string, and linked list.

So far, we have looked at only the linear data structures, like an array and linked list, but all information in the real world cannot be represented in a linear fashion, and that's where tree data structure helps.

34 at 34 for V5.34: Modern Perl Features for Perl’s Birthday

Friday, December 17, 2021, marked the thirty-fourth birthday of the Perl programming language, and, coincidentally, this year saw the release of version 5.34. There are plenty of Perl developers out there who haven’t kept up with recent (and not-so-recent) improvements to the language and its ecosystem, so I thought I might list a batch. You may have seen some of these before in May’s post “Perl can do that now!”

The feature Pragma

Perl v5.10 was released in December 2007, and with it came feature, a way of enabling new syntax without breaking backward compatibility. You can enable individual features by name (e.g., use feature qw(say fc); for the say and fc keywords), or by using a feature bundle based on the Perl version that introduced them. For example, the following:

The Bag Data Structure From Eclipse Collections

In computer science, a bag is defined as an abstract data structure, that allows keeping duplicate elements in any order. This is similar to a physical bag, where you could also put any elements and take them out randomly. So, bags are different from lists (because lists care about a particular position of an element) and from sets (because sets do not allow duplicates). The bag is a good choice when you just need to collect items and do some processing using iterations. Java does not offer its "vanilla" implementation of the bag, however, you could find it in popular collections libraries. In this post, we will review the Bag from Eclipse Collections, which supplies both mutable and immutable versions.

Create Bags

Before we will proceed with various Bag methods, let observe how to initialize a new Bag instance within the Eclipse Collections framework. Likewise to other types of collections, there are presented both mutable (modifiable) and immutable (non-modifiable) versions. In general, we can use the Bags class, which allows utilizing static factory methods to obtain bags:

  • Bags.immutable.* calls ImmutableBagFactory to create immutable bags.
  • Bags.mutable.* calls MutableBagFactory to create mutable bags.

Both types use the same approaches, that can be separated into the following three categories:

SKP’s Algorithms and Data Structures #9: Java Problem: Monkeys in the Garden

[Question/Problem Statement is the Property of Techgig] 

Monkeys in the Garden [www.techgig.com]

In a garden, trees are arranged in a circular fashion with an equal distance between two adjacent trees. The height of trees may vary. Two monkeys live in that garden and they were very close to each other. One day they quarreled due to some misunderstanding. None of them were ready to leave the garden. But each one of them wants that if the other wants to meet him, it should take maximum possible time to reach him, given that they both live in the same garden.

SKP’s Algorithms and Data Structures #8: Java Problem: Simple Inheritance (OOPs)

[Question/Problem Statement is the Property of Techgig]
 
Java Inheritance / Simple OOPs [www.techgig.com]
Create Two Classes:

BaseClass
The Rectangle class should have two data fields-width and height of int types. The class should have display() method, to print the width and height of the rectangle separated by space.

DerivedClass
The RectangleArea class is Derived from Rectangle class, i.e., it is the Sub-Class of Rectangle class. The class should have read_input() method, to Read the Values of width and height of the Rectangle. The RectangleArea class should also Overload the display() Method to Print the Area (width*height) of the Rectangle.

Input Format
The First and Only Line of Input contains two space-separated Integers denoting the width and height of the Rectangle.

Constraints
1 <= width,height <= 10^3

Output Format
The Output Should Consist of Exactly Two Lines.
In the First Line, Print the Width and Height of the Rectangle Separated by Space.
In the Second Line, Print the Area of the Rectangle.


[Explanation of the Solution]
This is the Simplest of all OOPs Questions! Demonstration of Inheritance and Overriding (Very Loosely, Liskov Substitution of SOLID).


[Source Code, Sumith Puri (c) 2021 — Free to Use and Distribute]
Java
 




x
67


1
 /*    
2
  * Techgig Core Java Basics Problem - Get Simple OOPs Right!  
3
  * Author: Sumith Puri [I Bleed Java!]; GitHub: @sumithpuri;  
4
  */   
5
     
6
  import java.io.*;   
7
  import java.util.*;   
8
   
9
   
10
  class Rectangle {  
11
   
12
    private int width;  
13
    private int height;  
14
   
15
    public void display() {  
16
   
17
      System.out.println(width + " " + height);  
18
    }  
19
   
20
    public int getWidth() {  
21
   
22
      return width;  
23
    }  
24
   
25
    public void setWidth(int width) {  
26
   
27
      this.width=width;  
28
    }  
29
   
30
    public int getHeight() {  
31
   
32
      return height;  
33
    }  
34
   
35
    public void setHeight(int height) {  
36
   
37
      this.height=height;  
38
    }  
39
  }  
40
   
41
  class RectangleArea extends Rectangle {  
42
   
43
    public void read_input() {  
44
   
45
     Scanner scanner = new Scanner (System.in);   
46
       
47
     setWidth(scanner.nextInt());   
48
     setHeight(scanner.nextInt());  
49
    }  
50
   
51
    public void display() {  
52
   
53
      super.display();  
54
      System.out.println(getWidth()*getHeight());  
55
    }  
56
  }  
57
     
58
  public class CandidateCode {   
59
     
60
   public static void main(String args[] ) throws Exception {   
61
     
62
     RectangleArea rectangleArea = new RectangleArea();  
63
     rectangleArea.read_input();  
64
   
65
     rectangleArea.display();  
66
   }   
67
 } 



SKP’s Algorithms and Data Structures #7: Functional Programming and Java Lambdas

[Question/Problem Statement is the Property of Techgig]

Java Advanced — Lambda Expressions [www.techgig.com] 
Write the Following Methods that Return a Lambda Expression Performing a Specified Action: Perform Operation isOdd(): The Lambda Expression must return if a Number is Odd or  If it is Even. Perform Operation isPrime(): The lambda expression must return if a number is prime or if it is composite. PerformOperation isPalindrome(): The Lambda Expression must return if a number is a Palindrome or if it is not.

Input Format
Input is as Show in the Format Below
Input
3
1 3
2 7
3 7777

Constraints
NA

Output Format
Output is as Show in the Format Below
Output
ODD
PRIME
PALINDROME


[Explanation of the Solution]
This is a Good Question to Refresh Java 8 Lambdas. In my Solution, I Implemented the Functional Interfaces within my main() Method and assigned it to Local Reference Variables.


SKP’s Algorithms and Data Structures #6: Java Problem: Active Traders

[Question/Problem Statement is the Property of HackerRank]

Algorithms/Data Structures — [Problem Solving] 
An Institutional Broker wants to Review their Book of Customers to see which are Most Active. Given a List of Trades By "Customer Name, Determine which Customers Account for At Least 5% of the Total Number of Trades. Order the List Alphabetically Ascending By Name."


Example
n = 23
"customers = {"Bigcorp", "Bigcorp", "Acme", "Bigcorp", "Zork", "Zork", "Abe", "Bigcorp", "Acme", "Bigcorp", "Bigcorp", "Zork", "Bigcorp", "Zork", "Zork", "Bigcorp", "Acme", "Bigcorp", "Acme", "Bigcorp", "Acme", "Littlecorp", "Nadircorp"}."

"Bigcorp had 10 Trades out of 23, which is 43.48% of the Total Trades."
"Both Acme and Zork had 5 trades, which is 21.74% of the Total Trades."
"The Littlecorp, Nadircorp, and Abe had 1 Trade Each, which is 4.35%..."

"So the Answer is ["Acme","Bigcorp","Zork"] (In Alphabetical Order) Because only These Three Companies Placed at least 5% of the Trades.


Function Description

Complete the Function mostActive in the Editor Below.

mostActive
has the following parameter:
String customers[n]: An Array Customer Names
(Actual Question Says String Array, But Signature is List of Strings)

SKP’s Algorithms and Data Structures #5: Java Problem: Changes in Usernames

[Question/Problem Statement is the Adapted from HackerRank]

Algorithms/Data Structures — [Problem Solving] 
There is a Specific Need for Changes in a List of Usernames. In a given List of Usernames — For Each Username — If the Username can be Modified and Moved Ahead in a Dictionary. The Allowed Modification is that Alphabets can change Positions in the Given Username.

Example
usernames[] = {"Aba", "Cat"}
 
"Aba" can be Changed to only "Baa" — Hence, It can Never Find a Place Ahead in the Dictionary. Hence, Output will be "NO". "Cat" can be Changed to "Act", "Atc", "Tca", "Tac", "Cta" and Definitely "Act" will Find a Place Before "Cat" in the Dictionary. Hence, Output will be "YES".

[Function Description]
Complete the function possibleChanges in the Editor Below.
 
possibleChanges has the Following Parameters:
String usernames[n]: An Array of User Names
 
Returns String[n]: An Array with "YES" or "NO" Based on Feasibility
(Actual Question Says String Array, But Signature is List of Strings)


Constraints
• [No Special Constraints Exist, But Cannot Recall Exactly]


Input Format 
"The First Line Contains an Integer, n, the Number of Elements in Usernames.",
"Each Line of the n Subsequent Lines (where 0 < i < n) contains a String usernames[i]."        

[Sample Case 0 — Sample Input For Custom Testing]         
5
Aba
Cat
Boby
Buba
Bapg
Sungi
Lapg
Acba
       
Sample Output (Each Should Be on a Separate Line) 
NO YES NO YES YES YES YES YES
   

 
[Explanation of the Solution]
This is again a Good Question from Hacker Rank to Test Your Logic / Problem Solving Abilities. The Core Point to Handle is that For Each Combination of 2 Alphabets that Exists in the Username String > We Need to Check if the Latter Occurring Character (ASCII) is Less than the Former Occurring Character (ASCII). For Example in the String "Bapg" — For a Selection of "Ba" from "Bapg" — We have "a" Occurring Before "B" in the English Alphabet. We can Have Two Loops (One Nested) to Decide for a Combination of Each Two Alphabets. The Time Complexity of this Solution is O(n^2).
 


[Source Code, Sumith Puri (c) 2021 — Free to Use and Distribute]

LJV: What We Can Learn From Java Data Structures Visualization

When I started to prepare a course of lectures on the Java language for the Moscow Institute of Physics and Technology, I became to search for material that can be used as illustrations. ‘One picture is worth a thousand words’ as they say, and sometimes it’s worth even more because it seems impossible to explain e. g. how a hash table works without drawing something. My task was to explain to students many Java concepts, from string pool to advanced data structures. I was looking for a solution that is able to make the visualization of Java data structures in the easiest and precise way, ideally compatible with ‘presentation as code’  technology.

There exists Aleksey Shipilev’s JOL (Java Object Layout) tool known among Java performance engineers. JOL analyzes the memory layout for any given object, including all the auxiliary data and fields, and the graph of objects reachable from the given instance. This tool gives accurate estimations of the object size and also shows the addresses in memory where objects are located. However, it’s not yet able to visualize the object graph and gives too many low-level details that are irrelevant for the students who just started to learn Java.

10 Examples of ConcurrentHashMap in Java

As a Java programmer, you might have heard about the ConcurrentHashMapclass of java.util.concurrent package. If you don't let me tell you that ConcurrentHashMap is an important class in Java and you will often find yourself dealing with this class in a multithreaded and concurrent Java application. If you are wondering where to start and how to master this essential Java class then you have come to the right place.

In this article, I have shared some of the frequently used examples of ConcurrentHashMap in Java-like how to create a ConcurrentHashMap, how to update a key or value, how to delete a key-value pair, how to check if a key exists in ConcurrentHashMap or not, how to add new key-value pairs, and how to retrieve values from ConcurrentHashMap in Java.

Once you have gone through these examples, you will have a better understanding of ConcurrentHashMap and you will be more confident in using them in your Java program without causing subtle bugs that are hard to find and fix.

C Programming Interview Questions

Most interview questions are based on algorithms and live coding. Companies know that learning a programming language or switching from one language to another should not be a problem for the candidate. But sometimes, for specific jobs, companies look for the candidate who specializes in a particular language. Here are some of the most frequently asked questions I have compiled that are asked during the interview for C developers.

C is a procedural programming language, used for writing effective programs. C is widely used language for the following reasons:

Variadic Template C++: Implementing Unsophisticated Tuple

From C++11, std::tuple is an incredible expansion to Modern C++ that offers a fixed-size col­lec­tion of het­ero­ge­neous values. Un­for­tu­nately, tu­ples can be somewhat dubious to manage in a conventional fash­ion. But, subsequently released C++ stan­dard in­tro­duced a few fea­tures and helpers that greatly re­duce the nec­es­sary boil­er­plate. 

So, in this article, I will explain the variadic template in C++ with the help of unsophisticated tuple implementation. I'll also walk you through a tricky part of tuple i.e. loop through tuple element. Because I have covered the variadic template in my prior article i.e. C++ Template: A Quick UpToDate Look, my focus here would be a blend of variadic template and tuple implementation with more up to date C++ gauges.

Graph BFS With Different DS in Adjacency Matrix and Their Usability

This article analyzes the adjacency matrix used for storing node-link information in an array. For a Graph BFS (Breadth-first-search) traversal, we normally tend to keep an adjacency matrix as a 2D array (adj[][]) or array of linkedLists as LinkedList[]. As a result, if an element X is added before element Y, it appears in BFS traversal accordingly. BFS traversal becomes like: ~X,Y,~. What if, the appearance of elements within a breath of a graph needs to be traversed  according to some priority or any rule!!

Say in a breath if Priority of Y > Priority of X, element Y should occur before X in BFS traversal. Say In a breath if Y is added later the X, Y should occur before X in traversal.

Understanding the Use Cases of Java Generics

Understanding general use cases of generics solves half of the problem. First things first, we should know what they are, why to consider them, and where they apply.

What Is It?

Consider a simple add method, seen below. You cannot pass long, float, or double types as inputs to this method, right?

Focus on Your Data Structures With Scala Lenses

With new programming techniques come new problems and new patterns to solve them.

In functional programming, immutability is a must. As a consequence, whenever it is needed to modify the content of a data structure, a new instance with updated values is created. Depending on how complex the data structure is, creating a copy may be a verbose task.

Immutable Data Structures in Java

As part of some of the coding interviews I’ve been conducting recently, the topic of immutability sometimes comes up. I’m not overly dogmatic in it myself, but whenever there’s no need for mutable state, I try to get rid of code which makes code mutable, which is often most visible in data structures. However, there seems to be a bit of a misunderstanding on the concept of immutability, where developers often believe that having a final reference, or val in Kotlin or Scala, is enough to make an object immutable. This blogpost dives a bit deeper in immutable references and immutable data structures.

Benefits of Immutable Data Structures

Immutable data structures have significant benefits, such as:

10 Things Every Programmer and Software Engineer Should Know

If you have been programming for some time and looking to learn to program then you might be thinking about what makes a good programmer. What can a computer science graduate do to prepare for a career in software development and programming? The things expected of a junior developer are some of the common questions I receive from many students on Facebook and Emails who follows me. These are mostly college students who now have access to a wealth of information thanks to the internet and eager to learn things in advance to prepare for their programming job interviews.

In this article, I'll share 10 things which I believe every programmer should know. This includes a programming language like C++ or Java, essential computer science concepts like data structures, algorithms and computer networking basics, essential tools like Git, Microsoft Word and Excel, skills like SQL and UNIX, editors like Eclipse or Visual Studio, and text editors.