April 30, 2020

#LeetCode: Check valid sequence from root to leaves in a BTree

Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Tree

Given a binary tree where each path going from the root to any leaf form a valid sequence, check if a given string is a valid sequence in such binary tree.

We get the given string from the concatenation of an array of integers arr and the concatenation of all values of the nodes along a path results in a sequence in the given binary tree.

#LeetCode: Binary Tree Maximum Path Sum

Given a non-empty binary tree, find the maximum path sum.

For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root.

April 28, 2020

#LeetCode: First Unique Number

You have a queue of integers, you need to retrieve the first unique integer in the queue.

Implement the FirstUnique class:
  • FirstUnique(int[] nums) Initializes the object with the numbers in the queue.
  • int showFirstUnique() returns the value of the first unique integer of the queue, and returns -1 if there is no such integer.
  • void add(int value) insert value to the queue.

#JWT: Part 3 - Spring Boot project with Spring Security and JWT Example

We will develop a Spring boot project with Spring security and JWt from scratch.

Objectives:
1). Create an API which will authenticate the user details and generate JWT token.
2). Functionality which will verify each request for the valid JWT.

#JWT: Part 2 - JWT Structure

What is JWT token?
JWT (JSON Web Token) is a safe, compact, and self-contained way of transmitting information between multiple parties in the form of a JSON object. It is used for authorization.

#JWT: Part 1 - Authorization Strategies, Real Life examples of Session and JWT Token

Authorization Strategies
HTTP is a stateless protocol that's why we need to send all the desired information each time, so that the server can authorize the request.

Let's say you are logged in tinder, while login you need to enter your user name and password. Tinder will verify if you are a valid user or not, if yes, it will start showing potential matches. Now if you right or left swipe on any profile, or do anything else on Tinder, it will send a request again to the Tinder server. Since HTTP is stateless, with each request you will asked to enter your credentials, which is quite irritating. To solve this problem, the session is managed.

April 27, 2020

#LeetCode: Maximal Square

Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area.

Example:

Input:
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0

Output: 4

April 26, 2020

Yash Pandit and Khushi Mukherjee roped in for Ullu App's Love Festival..

Ullu App is coming up with another interesting web-series which is based on partner exchange. The online streaming platform is all set to release another story of 'Riti Riwaj', which is titled 'Love Festival'. We heard, Yash Pandit and Khushi Mukherjee are roped in to play husband and wife in the series.

#LeetCode: Longest Common Subsequence

Given two strings text1 and text2, return the length of their longest common subsequence.

A subsequence of a string is a new string generated from the original string with some characters(can be none) deleted without changing the relative order of the remaining characters. (eg, "ace" is a subsequence of "abcde" while "aec" is not). A common subsequence of two strings is a subsequence that is common to both strings.

If there is no common subsequence, return 0.

April 25, 2020

#LeetCode: Java Solution of Jump Game problem

Given an array of non-negative integers, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Determine if you are able to reach the last index.

April 17, 2020

Veronica Vanij bags Ullu App's Smartphone

Online Streaming platform Ullu App is leaving no stone unturned to woo the viewers during quarantine. They are making the lockdown experience better with a varied offers and new editions of shows. Recently they launched the season 2 of its popular show Kavita Bhabhi, which received a massive response. Now they are gearing up to stream short film titled Smartphone.

Part 6: Elastic Search Interview Questions And Answers(Hands On)

Explain Bool Query in ElasticSearch.
A query that matches documents matching boolean combinations of other queries is called Bool Query. It is built using one or more boolean clauses, each clause with a typed occurrence. 

  • must: The clause (query) must appear in matching documents and will contribute to the score.
  • filter: The clause (query) must appear in matching documents. However unlike must the score of the query will be ignored. Filter clauses are executed in filter context, meaning that scoring is ignored and clauses are considered for caching.
  • should: The clause (query) should appear in the matching document.
  • must_not: The clause (query) must not appear in the matching documents. Clauses are executed in filter context meaning that scoring is ignored and clauses are considered for caching. Because scoring is ignored, a score of 0 for all documents is returned.

What is the difference between MUST and SHOULD bool query?
must means: The clause (query) must appear in matching documents. These clauses must match, like logical AND.
should means: At least one of these clauses must match, like logical OR.

In other words, results will have to be matched by all the queries present in the must clause or match at least one of the should clauses if there is no must clause.

What is the difference between MUST and FILTER bool query?
The must contributes to the score. In filter, the score of the query is ignored.

In both must and filter, the clause(query) must appear in matching documents. This is the reason for getting same result.

Examples:
To get list of all the bank accounts, execute:
GET bank/account/_search

To get all the bank acconuts from California (State will be CA):
GET bank/account/_search
{
  "query": {
    "match": {"state": "CA"}
  }
}

To get all the bank acconuts of Techade from California (State will be CA)
GET bank/account/_search
{
  "query": {
    "bool": {
      "must": [
        { "match": {"state": "CA"} },
        { "match": {"employer": "Techade"}}
      ]
    }
  }
}

To get all the bank acconuts not from Techade and outside California (State will be CA)
GET bank/account/_search
{
  "query": {
    "bool": {
      "must_not": [
        { "match": {"state": "CA"} },
        { "match": {"employer": "Techade"}}
      ]
    }
  }
}

-K Himaanshu Shuklaa..

Part 5: Elastic Search Interview Questions And Answers(Hands On)

How to check health of cluster and node?
Start ElasticSearch and Kibana, and then open Kibana dashboard (you can open it with this URL  http://localhost:5601/app/kibana#/dev_tools/console)

to check health of cluster execute:
GET _cat/health?v

April 16, 2020

Part 4: Elastic Search Interview Questions And Answers

What is ELK Stack and its contents?
Enterprises, large or small nowadays come across information in the form of reports, data and customer follow-ups and historical, current orders as well as customer reviews from the online and offline logs. It is essential to store and analyze these logs which will help predict valuable feedback for the businesses.

Part 3: Elastic Search Interview Questions And Answers

What is an Elasticsearch Analyzer? What are the various types of analyzers in Elasticsearch?
Analyzers are used for Text analysis, it can be either built-in analyzer or custom analyzer.

The analyzer consists of zero or more character filters, at least one Tokenizer and zero or more Token filters.

Part 2: Elastic Search Interview Questions And Answers

Explain the procedure to add or create an index in Elasticsearch Cluster?
To add a new index, create an index API option should be used. The parameters required to create the index is Configuration setting of an index, Fields mapping in the index as well as Index aliases.

Part 1: Elastic Search Interview Questions And Answers

Explain in brief about Elasticsearch?
Elasticsearch is an open-source, RESTful, scalable, built on Apache Lucene library, document-based search engine. It stores retrieve and manage textual, numerical, geospatial, structured and unstructured data in the form of JSON documents using CRUD REST API or ingestion tools such as Logstash.

April 14, 2020

How to pass command line arguments in Python?

Handling command line arguments with Python
  • There are number of different ways of handling command line arguments in Python 3. 
  • 'sys' module is the built-in way. 
  • We can also use getopt module, which handles both short and long options, including the evaluation of the parameter values.
  • argparse module, which is derived from the optparse module available up to Python 2.7, we can also use it to handle command line arguments.
  • The other method is using the docopt module, which is available on GitHub.

April 03, 2020

#Collections: Part 8(Time Complexity And Performance of Java Collections)

ArrayList
The ArrayList in Java is backed by an array.
  • add() takes O(1) time
  • add(index, element) in average runs in O(n) time
  • get() is always a constant time O(1) operation
  • remove() runs in linear O(n) time. We have to iterate the entire array to find the element qualifying for removal
  • indexOf() also runs in linear time. It iterates through the internal array and checking each element one by one. So the time complexity for this operation always requires O(n) time
  • contains() implementation is based on indexOf(). So it will also run in O(n) time

#Collections: Part 7 (All about Exchanger in Java)

java.util.concurrent.Exchanger < T > class in Java can be used to share objects between two threads of type T. It provides only a single overloaded method exchange(T t).

#Collections: Part 6 (All About SynchronousQueue in Java)

SynchronousQueue from the java.util.concurrent package allows us to exchange information between threads in a thread-safe manner.

SynchronousQueue is a special kind of BlockingQueue in which each insert operation must wait for a corresponding remove operation by another thread and vice versa.

It has two supported operations: take() and put(), and both of them are blocking.

April 02, 2020

#Collections: Part 5 (Hashmap implementation in pre-Java 8 and Java 8)

What is the difference in Hashmap implementation in pre-Java 8 and Java 8?


There is no change to how the Java developer uses and implements HashMap < K, V > . In Java 8, they have made some internal changes in HashMap, well that changes not only affect HashMap but also, LinkedHashMap, and ConcurrentHashMap.

a). The alternative String hash function added in Java 7 has been removed in Java 8. The default hash formula on strings was optimized to being both faster and allow for less clashes on average. Thus if your key is a string (someone’s name in a contacts list), it should calculate that hash faster than before and the likelihood that it would calculate a hash pointing to the same bucket is less.

b). Buckets containing a large number of colliding keys will store their entries in a balanced tree instead of a linked list after a certain threshold is reached.

#Collections: Part 4 (How ConcurrentHashMap Works Internally in Java?)

What is ConcurrentHashMap?
ConcurrentHashMap class is introduced in JDK 1.5, which implements ConcurrentMap as well as Serializable interface also.

It is a thread-safe implementation of the Map interface provided by Java's concurrency package (java.util.concurrent). It allows concurrent access to the map without the need for external synchronization.

Segment, which is internal data structure and part of map is locked while adding or updating the map. Due to this the ConcurrentHashMap allows concurrent threads to read the value without locking at all. This data structure was introduced to improve performance.

Happy Birthday Ram!!


Happy Birthday Ram ❤️
भये प्रकट कृपाला दीन दयाला कौशल्या हितकारी ,
हर्षित महतारी मुनि मन हारी अद्भुत रूप बिचारी ।।

April 01, 2020

Part 1: Node JS Tutorial-var vs let vs const in JavaScript

While declaring any variable we can use either var, let or const. In JavaScript, variables are initialized with the value of undefined when they are created. What that means is if we try to log the declaration variable, we’ll get undefined. e.g:

var name;
console.log(name); // this will print 'undefined'

Part 2: Node JS Tutorial- Understanding npm

Write your own module
Open visual studio code, create a new file with the name my-module.js. Let's create another file module-demo.js. We will declare a variable inside my-module.js and try to access it from module-demo.js.

In my-module.js, we have declared variable mytext.

How to Convert PDF to Image using Python?

We can user pdf2image library in Python 3 for converting image. This library wraps pdftoppm and pdftocairo to convert PDF to an image object.

#Collections: Part 3- All about PriorityQueue in Java

What is PriorityQueue in Java?
  • A queue follows First-In-First-Out algorithm, in case of PriorityQueue queue elements are processed according to the priority (ordered as per their natural ordering or based on a custom Comparator supplied at the time of creation).
  • The PriorityQueue is based on the priority heap.
  • We can’t create PriorityQueue of Objects that are non-comparable
  • Inserting null into a PriorityQueue will throw a NullPointerException, as PriorityQueue in Java does not permit null elements.
  • PriorityQueue are unbound queues.
  • The head of this queue is the least element with respect to the specified ordering. If multiple elements are tied for least value, the head is one of those elements — ties are broken arbitrarily.
  • The queue retrieval operations poll, remove, peek, and element access the element at the head of the queue.
  • PriorityQueue inherits methods from AbstractQueue, AbstractCollection, Collection and Object class.
  • Inserting an element (offer()) and deleting an element (poll()) in a PriorityQueue both have a time complexity of O(log n), where n is the number of elements in the queue.
  • The default PriorityQueue is implemented with Min-Heap, which means the top element is the minimum one in the heap. If we want to implement a max-heap, we need to use our custom Comparator.
  • Internally, the PriorityQueue in Java uses an array to store its elements. This array automatically grows in size if the initial capacity (which is 11 by default in JDK 17) is not large enough to hold all the elements added to the queue. 
  • While you don't have to specify an initial capacity when creating a PriorityQueue, if you know how many elements you'll be adding ahead of time, it's beneficial to set an initial capacity. This helps prevent the queue from frequently resizing, which can use up unnecessary CPU resources that could be better utilized elsewhere.
Can you provide an example scenario where a PriorityQueue would be useful?
A PriorityQueue can be used in scenarios such as task scheduling in an operating system, where tasks with higher priority need to be executed before those with lower priority.

PriorityQueue Constructors
  • PriorityQueue(): Creates a PriorityQueue with the default initial capacity (which is 11) that orders its elements according to their natural ordering.
  • PriorityQueue(Collection c): It creates a PriorityQueue containing the elements in the specified collection.
  • PriorityQueue(int initialCapacity): Creates a PriorityQueue with the specified initial capacity that orders its elements according to their natural ordering.
  • PriorityQueue(int initialCapacity, Comparator comparator): Creates a PriorityQueue with the specified initial capacity that orders its elements according to the specified comparator.
  • PriorityQueue(PriorityQueue c): Creates a PriorityQueue containing the elements in another priority queue.
  • PriorityQueue(SortedSet c): Creates a PriorityQueue containing the elements in the specified sorted set.
PriorityQueue operations
  • boolean add(E element)inserts the specified element into this priority queue.
  • boolean offer(E e) method is used to insert a specific element into the priority queue.
  • public peek() retrieves, but does not remove, the head of this queue, or returns null if this queue is empty.
  • public poll() retrieves and removes the head of this queue, or returns null if this queue is empty.
  • public remove() removes a single instance of the specified element from this queue, if it is present. When we remove an element from the priority queue, the least element according to the specified ordering is removed first.
  • Iterator iterator() returns an iterator over the elements in this queue.
  • boolean contains(Object o) method returns true if this queue contains the specified element
  • void clear() is used to remove all of the contents of the priority queue.
  • int size() returns the number of elements present in the set.
  • toArray() is used to return an array containing all of the elements in this queue.
  • Comparator comparator() method is used to return the comparator that can be used to order the elements of the queue.
What is the difference between offer and add methods of PriorityQueue?
  • offer() and add() are two ways to insert data into a PriorityQueue.
  • In Queues, the add is used to insert a specified element into the queue. It returns true when the task is successful or else it throws an exception. offer() is also used to insert a specified element into the queue. But it returns true when the task is successful or else its return false.
  • In the case of PriorityQueue, the add method behaves identically to offer() in a PriorityQueue. If you see the implementation, the add method of PriorityQueue is internally calling offer.

GIT URL: PriorityQueue Example in Java
Priority Queue Example
-K Himaanshu Shuklaa..