March 2021

The launch of coinlayer, an API that integrates real-time crypto rates on websites and applications, has made it easier for developers to provide exchange rates for over 385 cryptocurrencies.

One of the most-watched markets globally is the cryptocurrency market, and the rising interest of investors has made it crucial to provide reliable cryptocurrency data in real-time.

Due to the extreme uncertainty found in most cryptocurrencies, the price would typically not be the same from day to day. You need an app, service, or platform that can provide rates every hour. Coinlayer offers this kind of service against several fiat currencies for over 385 different coins.

Developers, Blockchain experts, and crypto affiliates can add crypto rates to websites using the coinlayer API. Besides, coinlayer has opened the window of opportunity, being an API that any average person can use.

Introduction to coinlayer

coinlayer

coinlayer is the most trusted and authoritative resource for accurate crypto market data from more than 25 exchange rates. There are three main features in the coinlayer API, including performance, ease of use, and compatibility.

The use of the coinlayer includes:

  • An easy REST framework
  • Comprehensive and interactive API documentation
  • Integration guides
  • Real-time Cryptocurrency
  • JSONExchange Rates
  • Response time up to 20 milliseconds

The best part!

coinlayer is also free to use. However, the free version has certain limitations, and one has to pay the price to go fully featured. Nevertheless, the pricing for coinlayer is not as high as other crypto market data APIs that come with high monthly fees, no customer support, and a low monthly quota.

Check the pricing!

coinlayer Pricing

coinlayer Pricing

The platform offers different plans for different needs. The free plan undoubtedly is entirely free without any hidden charges. Additionally, as per your requirements, you can opt from the following available premium plans:

  • Basis: $9.99 per month/ $95.90 per year
  • Professional: $39.99 per month/ $383.90 per year
  • Professional Plus: $79.99 per month/ $767.90 per year
  • Enterprise: Contact Sales

coinlayer Features

Extensive Cryptocurrency Database

Collect up-to-date data on the cryptocurrency, accessed from 25+ markets, spontaneously on more than 385 coins.

Traditional Data

Examine how the API has been developed for historical data during 2011 by querying cryptocurrency data over time.

Robust JSON API

A solid and highly accessible cloud platform supports the coinlayer API, which delivers the data in milliseconds.

Authoritative Sources

Many reputable crypto-exchange providers influence crypto rates for coinlayer API to ensure maximum precision.

Dedicated Support

The team of experts at coinlayer takes customer support very sternly to help users understand from the basic to the advanced level in cryptocurrency.

Bank-Grade Security

The coinlayer API protects both request and response data transmission through the 256-bit HTTPS industry-standard encryption.

So, let’s get started with understanding how to add crypto rates to your website using coinlayer.

How to Add Crypto Rates to your Website using coinlayer?

coinlayer API

The API for coinlayer comprises a series of endpoints, functionalities, and options. coinlayer obtains crypto data from some of the biggest cryptocurrency exchanges that are requested using HTTP GET. The accuracy and reliability of the crypto data returned by the coinlayer API are the strongest owing to its sophisticated fallback algorithm.

coinlayer Quickstart Tool

The onboarding for beginners is made simple with a Quickstart tool, which displays all of the functionality of the API. If signed up, you can use their Quickstart Tool to evaluate every API endpoint with a tap.

Besides, it would help if you had a free API access key to start using the Quickstart tool.

Achievable Target Currencies

By default, the coinlayer API still converts cryptocurrency rates to American dollars. Using the target API to shift the objective currency to some other approved fiat currency code can be done by customers subscribing to the basic or higher plan.

A total of 166 world currency conversions are supported by the coinlayer API. Contrary to other related APIs where time differences could be required, coinlayer operates out of the box for every marked project.

An example of target currency code for Euro:

[...]

& target = EUR

[...]

You can find a list of all supported target currency codes here.

Response Objects

Check out the below list of response objects for coinlayer API and their description:

Response Objects

Getting Started with coinlayer API

API Access Key

Your API access key is the only token for accessing the coinlayer API. By signing in to the dashboard, you must search your API access key.

Upon completion of your registration, a forever free API key will be issued. This is more than enough for training and should be sufficient enough for essential use.

Further, you get a window to validate the API after logging in. The database query will be running, and the data can be expanded through the endpoints for all available JSON cryptocurrencies. For convenience, the required query parameters are highlighted with orange and optional parameters with blue.

To authenticate the API, append the access_key parameter to the API’s base URL and set it to your API access key value.

Base URL: https://ift.tt/3sFVc55

Append your API Access Key:

https://api.coinlayer.com/live
? access_key = YOUR_ACCESS_KEY

The main configuration is the base URL (https://ift.tt/3sFVc55), the endpoint (live, list, convert, etc.), and the API’s permission key. The response returns the question performance status, links to terms and privacy sites, unique endpoint features, destination currencies, and specific endpoint datasets. The coinlayer supports JSON callbacks so that the GET callback optional parameter will wrap the result within a function.

API Response

As you can see above, we have used the Live endpoint while appending the API access key. So, the basic API response for all available cryptocurrencies is shown below in JSON format with the exchange rate data:

API Response

Reviewing coinlayer API Endpoints

Overall, six API endpoints, each with different functionality, are available in the coinlayer API.

1. Live Data

This endpoint is used to query the API for the latest available exchange rate data.

API Request Example:

https://api.coinlayer.com/live
? access_key = YOUR_ACCESS_KEY

API Response Example:

Live Data

2. Historical Data

By using this endpoint, crypto rates for a specific date can be fetched.

API Request Example:

https://api.coinlayer.com/2018-04-30
? access_key = YOUR_ACCESS_KEY

API Response Example:

Historical Data

3. Conversion Endpoint

It helps in converting amounts between cryptocurrencies and target currencies.

API Request Example:

https://api.coinlayer.com/convert
? access_key = YOUR_ACCESS_KEY
& from = BTC
& to = ETH
& amount = 10

API Response Example:

Conversion Endpoint

4. Time-Frame Data

To fetch the data for a specific period, Time-Frame data is used.

API Request Example:

https://api.coinlayer.com/timeframe
? access_key = YOUR_ACCESS_KEY
& start_date = 2018-04-01
& end_date = 2018-04-30
& symbols = BTC,ETH

API Response Example:

Time-Frame Data

5. Change Data

This endpoint retrieves data about rate fluctuation for a specific period.

API Request Example:

https://api.coinlayer.com/change
? access_key = YOUR_ACCESS_KEY
& start_date = 2018-04-01
& end_date = 2018-04-30
& symbols = BTC,ETH,XRP

API Response Example:

Change Data

6. List Endpoint

To retrieve a list of all available cryptocurrencies and target currencies, the List endpoint is available.

API Request Example:

https://api.coinlayer.com/list
? access_key = YOUR_ACCESS_KEY

API Response Example:

List Endpoint

Conclusion

Developers can use coinlayer for incorporating a feature for crypto-monetary trade into their websites or smartphone applications for a financial or digital money trading firm. Coinlayer is the optimal solution for all applicable cryptocurrencies in real-time, stable exchange rates.

Anyone who seeks to integrate live reference prices into their ventures must take the coinlayer API into account.

Cheers to coinlayer!

The post coinlayer API Review – How to Add Crypto Rates to Your Website appeared first on The Crazy Programmer.



from The Crazy Programmer https://ift.tt/3sH8caF

ROM is Read-Only Memory and the most important type of electronic storage, which comes in-built to the device during manufacturing. You must have seen ROM chips in your computers and other electronic products; game consoles, VCRs, and even car radios all of them use ROM for completing their functions effectively and smoothly.

ROM chips generally come built-in the external unit – just like flash drives or other auxiliary devices –and are installed in the hardware of a device on the removable chip. The non-volatile memory of ROM stays viable even without the power supply. In this post, we will learn more about ROM and different types of ROM to check out:

What is ROM

ROM is a solid-state memory that will read-only data stored. Its feature is that when data gets stored, it will not be changed and deleted. As mentioned before, it is mainly used in the computer and various electronic devices, even though the power gets turned off, data won’t disappear. The widely used type of primary storage is a volatile form of RAM or random access memory that means content present in RAM can be lost if power gets turned off.

Though ROM is a type of non-volatile memory, it’s not appropriate for use as the primary storage because of some limitations. Generally, the non-volatile memories can be expensive, have got lower performance, and have a limited lifetime when compared to the volatile RAM.

How Does ROM Work?

For its important characteristics like data stored in a ROM is written after manufacture to be read during its working process, rather than being rewritten fast and conveniently like the random memory.

Thus, whatever data gets stored in a ROM will be stable, and stored data will not change even after the power is off; this structure is simple, and reading is convenient, therefore it is used for a task of secondary storage, and long-term storage to store different fixed data and programs.

The CPU reads data only in ROM and traditionally, it has not been possible to modify any data in ROM. But, some ROM chips have rewrite abilities, so data can easily be erased from different kinds of ROM. But, data cannot be rewritten and erased nearly as fast as with RAM.

Way ROM Work During the Bootstrapping Process

Whenever you press a power button, the BIOS chip awakens & checks the different components of the system to ensure they are present and working in the right way. In the process known as a power-on test, BIOS instructs your CPU to check code at various locations. During this test, you may hear the whining of the hard drive & see flashing lights. After this test is done, CPU takes over & launches an operating system.

Different Types of ROM

Different Types of ROM

Image Source

Now, let’s go ahead and discuss different kinds of ROMs and their characteristics.

MROM (Masked Read Only Memory)

The first ROMs were the hard-wired devices, which have the pre-programmed data set and instructions. These types of ROMs are called as masked ROMs that cheap.

PROM (Programmable ROM)

PROM can easily be modified once by the user. They can buy the blank PROM & enters desired contents by using the PROM program. Inside a PROM chip, there’re small fuses that are burnt open at the time of programming. This can be programmed just once and cannot be erased. The blank PROM chip enables current to run over all possible pathways, and the programmer selects the pathway for current just by sending the high voltage over unwanted fuses for “burning” it out. Static electricity will create a similar effect by accident, thus PROMs are highly vulnerable to damage than conventional ROMs.

EPROM (Erasable & Programmable ROM)

EPROM can easily be erased just by exposing this to the ultra-violet light and that also for around 40 minutes. Generally, an EPROM eraser attains this function. During the programming, the electrical charge gets trapped in the insulated gate area. This charge can be retained for over 10 years because the charge has got no leakage path. To erase the charge, the ultra-violet light will be passed through the quartz crystal window. And this exposure to UV light dissipates its charge. During normal use, the quartz lid gets sealed with the sticker and this exposure renders a chip blank again, then you may reprogram it as per the similar process as the PROM. The EPROM chips can wear out eventually, however they often have lifetimes of more than 1000 erasures.

EEPROM (Electrically Erasable & Programmable ROM)

EEPROM can be programmed & erased electrically. This type of ROM can be erased & reprogrammed around ten thousand times. Erasing & programming take 4 – 10 milliseconds. In the EEPROM type, any location is selectively erased or programmed. Also, EEPROMs can get erased just 1 byte at a time, instead of erasing the whole chip. Thus, the reprogramming process will be flexible and slow.

FLASH ROM

It’s the advanced EEPROM version and stores information in the arrangement or range of the memory cells that are made from the floating-gate transistors. One primary benefit of using such memory is you may delete and write blocks of the data over 512 bytes at one time. While, in EEPROM, you may delete or write just 1-byte data at a particular time, thus, this memory type is much faster than the EEPROM.

This memory can be reprogrammed without even removing this from your computer. The access time is a bit high, over 45 – 90 nanoseconds. It’s highly durable since it can easily bear high temperature & intense pressure.

Some Examples of ROM

There’re a few real-life ROM examples, let us see each one:

  • ROM is used in electronics devices such as feature phones Nokia 3310, Handy Games, DVD, VCR, Digital Watches, or more.
  • Because of the permanent data storage, ROM can be used in different kinds of the embedded system as in the embedded system, it doesn’t need changing data.
  • It can also be used in automobiles, where you need data, so data will be saved in a chip.
  • ROM can also be used in various home appliances like microwave, TV, washing machine, refrigerator, and more.
  • ROM can be used in automation toys like singing fish toy and in this particular toy, you can store the preplanned program when push the buttons to generate music.
  • It’s used in various other devices like printers, calculators, FAX machines, plotters, etc.

Share your thoughts about the article in the comment section below.

The post Different Types of ROM appeared first on The Crazy Programmer.



from The Crazy Programmer https://ift.tt/3m28Ywt

In this article, we will have a look at another interesting algorithm related to Graph Theory – Boruvka’s Algorithm. We will also look at a problem with respect to this algorithm, discuss our approach and analyze the complexities.

Boruvka’s Algorithm is mainly used to find or derive a Minimum Spanning Tree of an Edge-weighted Graph. Let us have a quick look at the concept of a Minimum Spanning Tree. A Minimum Spanning Tree or a MST is a subset of edges of a Weighted, Un-directed graph; such that it connects all the vertices together. The resultant subset of the graph must have no cycles or loops within it. Moreover, It should have minimum possible total weight of the edges connecting the tree.

Note: The Minimum Spanning Tree should connect all its vertices. A disconnected graph is not a MST.

Let us understand this with an example, consider this graph:

Boruvka's Algorithm

The above shown graph is an Edge-Weighted, undirected graph with 6 vertices. The minimum Spanning tree of the above graph looks like this:

Boruvka's_MST

Explanation:

The above image shows the Minimum Spanning tree of Graph G, as it connects all the vertices together. The resultant graph has no loops or cycles within it. After trying out various examples we select the smallest edge from each vertex and connect the two vertices together. We avoid connecting those edges which are already processed as it may form a cycle. The Minimum Possible Weight obtained from this MST adding all the weights from respective edges: 1 ( Edge 1 to 2 ) + 4 ( Edge 1 to 4 ) + 5 ( Edge 2 to 3 ) + 3 ( Edge 2 to 5 ) +2  (Edge 5 to 6 ); so Total Weight of MST = 15.

Note: The Maximum Number of Edges present in a Minimum Spanning Tree = Number of Vertices – 1.

Boruvka’s Algorithm

Now let us see how Boruvka’s Algorithm is helpful in finding the MST of a graph.

  • The idea is to separate all nodes at first, then process each node one by one by connecting nodes together from different components.
  • For each node, we find the edge with least weight and connect them to form a component. Then we jump to the next vertex.
  • After this, for each component, we choose the smallest or cheapest edge so that we get disconnected components of graphs. Then we combine the graph using the above process. If any loop or cycle found we ignore those edges.
  • After getting all the disconnected components we try connecting them following the above steps. Each repetition of this process reduces the number of nodes, within each connected component of the graph, to at most half of this former value, so after logarithmically many repetitions the process finishes.
  • At the end, the weight of edges we add from the Minimum Spanning Tree.

Implementation in Java

Step 1:

We represent the Graph using a class with three fields: V, U, and Cost. V is the source vertex , U is the destination and Cost is the weight between V and U. We use two arrays Parent and Min. The Parent Array stores the parent of node and Min stores the Minimum outgoing edge for each pair (v,u). For ith node we initialize its parent value to the same node.

Step 2:

At first we set the number of Components to the number of vertices n. For each component we initialize Min as -1, indicating there is no cheapest edge. For each node in our graph if its source and end vertex are part of same component we do not process them. Otherwise, for each vertex we take their root or parent node and check if it is minimum weighted edge.

Step 3:

Then, we iterate through each component, if there is an each edge for pair (u,v) we merge them into a single component. Before merging we check if the nodes are from same component, on doing this we avoid merging two nodes into same component which might create a loop or cycle. If we are able to merge the two components we add their edge weight. We repeat these steps for each component. This makes sure all edges are visited at least once and on each iteration, we skip (log n) number of nodes.

Now let us look at the implementation of the above in Java code:

import java.util.*;

class Graph_Edge
{
    int v;
    int u;
    int cost;
    Graph_Edge(int v,int u,int cost)
    {
        this.v=v;
        this.u=u;
        this.cost=cost;
    }
}

public class Boruvka_MST
{
  static int parent[] = new int[7];
  static int Min[] = new int[7];

  public static void main(String args[]) 
  {
  // No. of vertices in graph.
  int n=6;     
  Graph_Edge g[]=new Graph_Edge[10];
  
  // Creating the graph with source, end and cost of each edge
  g[1]=new Graph_Edge(1,2,1);
  g[2]=new Graph_Edge(1,4,4);
  g[3]=new Graph_Edge(2,4,7);
  g[4]=new Graph_Edge(2,5,3);
  g[5]=new Graph_Edge(2,6,6);
  g[6]=new Graph_Edge(3,2,5);
  g[7]=new Graph_Edge(3,6,9);
  g[8]=new Graph_Edge(6,5,2);
  g[9]=new Graph_Edge(5,4,8);
  
  // Initializes parent of all nodes.
  init(n);
  
  int edges = g.length-1;
  
  int components = n;
  int ans_MST=0;
  
  while(components>1)
  {
      // Initialize Min for each component as -1.
      for(int i=1;i<=n;i++)
      {
          Min[i]=-1;
      }
      for(int i=1;i<=edges;i++)
      {
          // If both source and end are from same component we don't process them.
          if(root(g[i].v)==root(g[i].u))
          continue;
          
          int r_v=root(g[i].v);
          if(Min[r_v]==-1 || g[i].cost < g[Min[r_v]].cost)
          Min[r_v]=i;
          
          int r_u=root(g[i].u);
          if(Min[r_u]==-1 || g[i].cost < g[Min[r_u]].cost)
          Min[r_u]=i;
          
      }
      
      for(int i=1;i<=n;i++)
      {
          if(Min[i]!=-1)
          {
              if(merge(g[Min[i]].v,g[Min[i]].u))
              {
                  ans_MST+=g[Min[i]].cost;
                  components--;
              }
          }
      }
  }
  
  System.out.println("The Total Weight of Minimum Spanning Tree is : "+ans_MST);
  
  }

  static int root(int v)
  {
      if(parent[v]==v)
      return v;
      
      return parent[v]=root(parent[v]);
  }
  
  static boolean merge(int v,int u)
  {
      v=root(v);
      u=root(u);
      if(v==u)
      return false;
      parent[v]=u;
      return true;
  }

  static void init(int n)
  {
      for(int i=1;i<=n;i++)
      {
          parent[i]=i;
      }
  }
  
}

Output:

The Total Weight of Minimum Spanning Tree is : 15

Note: We take Graph array of size 10 for total no. of edges are 9 as discussed in the example above and vertices are named from 1. The same is for Parent and Min array, we take size 7 for 6 vertices.

We have implemented the code for the same example as shown above. Now let us have a quick look at the complexities.

Time Complexity: For N nodes of graph, we have E edges to check the minimum weighted edge we have to iterate through all the edges and on each iteration the total nodes to be processed decreases logarithmically. So the overall complexity is O( E * log(N) ) .

Space Complexity: We require extra space to store the Parent and Min edge with respect to each node in our graph of size equal to the total number of vertices N. So the overall complexity is O(N).

Limitation Of Boruvka’s Algorithm

We can see in the above example that we used the graph with edges having distinct weight. This is a limitation for this algorithm which requires the graph to be Edge-Weighted but with Distinct Weights. If edges do not have distinct weights, then a consistent tie-breaking rule can be used. An optimization is to remove each edge in Graph G that is found to connect two vertices in the same component as each other.

So that’s it for the article you can try out this algorithm and dry run with various examples to have a clear idea. You can also execute this code to have a better understanding.

Feel free to leave your suggestions/doubts in the comment section below.

The post Boruvka’s Algorithm with Implementation in Java appeared first on The Crazy Programmer.



from The Crazy Programmer https://ift.tt/3csxfbM

A credential stuffing attack is a cybercrime technique where attackers use automated scripts and try them on a targeted website. It happens because the majority of users repeat similar credentials on more than one account. That means one data threat can also threaten several others. The attackers use tools like Sentry MBA to test such certificates in the highly automated bulk effort. Sometimes theft succeeds in login in allowing them to take advantage of services, stored credit card numbers, and other personal information.

The attackers inject username and password pairs to try unauthorized access to user accounts. Therefore, organizations need to stress the importance of using different passwords if one has more than one account. Using duplicate passwords for different accounts can be hazardous because once the hackers get to know one of the passwords; they will get access to any of your other accounts.

When you understand different ways that attackers use to access your business information, you will do everything possible to keep them at bay. Attackers are dangerous to any business as they can use that to bring down your business.

Credential Stuffing Attacks

Image Source

How to Detect Credential Stuffing

You can use multiple ways of detecting credential stuffing that you can apply to prevent any stuffing attack on your business. Here are examples of what you can do to catch the stuffing attack.

Several Login Attempts

Monitor your account and find out whether you can note several login attempts. Most of the multiple attempts happen when someone who is not the account owner tries several login credentials just if one of them will be accepted by the system. It can either be from one endpoint or several endpoints.

Separate IP Addresses

Detect known malicious endpoints attempting to log in using separate IP addresses or fingerprinting techniques. Also, check for automation of software in the login processes. Avoid scenarios where your company’s employees want to use various devices to log in to your system.

Removal Credential Attempt

Look for any attempts to remove credential-based login and to replace it with password-less authentication.

Tips on Preventing Credential Stuffing Attack

Use the following tips to keep attackers away from using credential stuffing attack on your business:

Multi-Factor Authentication

Multi-factor authentication (MFA) is one of the most effective ways of protecting your credential stuffing. It works by asking users to use additional authentication like using mobile as a defence to credential stuffing. The attacker bots are not capable of providing physical authentication method such as mobile phones. Most of them cannot even work with multiple authentications. Combining your authentication process with other techniques gives the attackers a hard time and prevents credential stuffing attacks.

Use of CAPTCHA

Use of CAPTCHA is another way of making sure the attackers do not access your account. The process of using the CAPTCHA requires users to perform specific actions to prove that they are human. That is an effective way of reducing credential stuffing attacks. However, the CAPTCHA method has limitations and can only be used in specific scenarios.

Use of Email Address

Avoid using email addresses as user IDs as the credential stuffing relies on the reuse of usernames or account IDs. User stuffing attack is most likely when you are using their email address as an account ID. Disallowing email ID is one of the most effective ways of reducing the credential stuffing attack.

The attackers use an account checker to try the stolen credentials on multiple websites like social media or online marketplaces. If the attempt works, the attacker can match different accounts with the stolen credentials. That is a quick way of draining the stolen account of any stored value like the credit card numbers or any other personally identifiable information. Using the stolen credentials, the attacker can create other transactions.

How to Use Imperva Bot Management as a Preventive Measure for Credential Stuffing Attacks

Imperva provides multi-layered protection to ensure that websites and applications are available and easy to access and keep them safe. The Imp[erva application works in the following ways:

DDoS Protection

DDoS maintains uptime in all cases preventing any type of DDoS attack by hindering access to your website and network infrastructure. Attackers can use your downtime to attack your accounts.

CDN Protection

CDN enhances website performance while reducing bandwidth costs with CDN-designed developers. You can also accelerate APIs and dynamic websites. It is essential to make sure that your business is protected at all times from any form of credential attacks.

WAF

Cloud-based solutions are effective in permitting traffic and preventing bad traffic, thus safeguarding applications at the edge. The best thing with is that it keeps applications and APIs in your network safe.

API Security

The IPS security is essential for protecting APIs by ensuring only the desired traffic can access your endpoint and keep everybody else away. It also detects and blocks your website from exploits of vulnerability.

There are several other methods of protecting the credential stuffing of your account. However, it is essential to make sure that you use the most effective and easy-to-use method. Sometimes it calls for multiple prevention measures just to make sure that you are completely protected. Your business needs proper protection from the credential stuffing attack as well as all the other cybersecurity attacks. Cybersecurity is critical for every business as a breach of security can break your business.

Regardless of the method you choose to protect your business, one most effective prevention method is making sure the employees are well trained. It is essential to train the staff and make sure they understand the effect of cyber attacks and how they can change everything in your business. Attackers can bring down your business in different ways.

They can steal not only important information but also business valuables like transferring money from accounts. They can also bring your business down by tinting your reputation. When customers and suppliers hear that you have been attacked, they will lose confidence in you and eventually limit their transactions with you. That will be the beginning of your business downfall and can lead to a collapse of your business.

The post Credential Stuffing Attacks – Definition, Detection and Prevention appeared first on The Crazy Programmer.



from The Crazy Programmer https://ift.tt/3rtHVvb

In this article, we will look at a famous algorithm in Graph Theory, Tarjan Algorithm. We will also look at an interesting problem related to it, discuss the approach and analyze the complexities.

Tarjan’s Algorithm is mainly used to find Strongly Connected Components in a directed graph. A directed graph is a graph made up of a set of vertices connected by edges, where the edges have a direction associated with them.  A Strongly Connected Component in a graph is basically a self contained cycle within a directed graph where from each vertex in a given cycle we can reach every other vertex in that cycle.

Let us understand this with help of an example, consider this graph:

Tarjan Algorithm

In the above graph, the box A and B show the SCC or Strongly Connected Components of the graph. Let us look at a few terminologies before explaining why the above components are SCC.

  • Back-Edge: So an edge of nodes (u,v) is a Back-Edge, if the edge from u to v has Descendent-Ancestor relationship. The node u is the descendant node and node v is the ancestor node. In this case, it results in a cycle and is important in forming a Strongly Connected Component.
  • Cross-Edge: An edge (u,v) is a Cross-Edge, if the edge from the u to v has no Ancestor-Descendent relationship. They are not responsible for forming a SCC. They mainly connect two SCC’s together.
  • Tree-Edge: If an edge (u,v) has a Parent-Child relationship such an edge is Tree-Edge. It is obtained during the DFS traversal of the tree which forms the DFS tree of the graph.

Explanation:

So, in the above graph edges -> (1 , 3), (3 , 2), (4 , 5), (5 , 6), (6 , 7) are the tree edges because they follow the Parent-Child Relationship. Edges -> (2 , 1) and (7 , 4) form the back edges because from node 2 (Descendent) we go back to 1 (Ancestor) completing a cycle (1->3->2). Similarly, from edge 7 we go back to  4 completing a cycle ( 4-> 5 -> 6 ->7). Hence the components (1,3,2) and (4,5,6,7) are the Strongly Connected Components of the graph. The edge (3 , 4) is a Cross edge because it follows no such relationship and connects the two SCC’s together.

Note: A Strongly Connected Component in a graph must have a Back-Edge to its head node.

Tarjan’s Algorithm

Now let us see how Tarjan’s Algorithm will help us find a Strongly Connected Component.

  • The idea is to do a Single DFS traversal of the graph which produces a DFS tree.
  • Strongly Connected Components are the subtrees of the DFS tree. If we find the head of each subtrees,  we can get access to all the nodes in the subtree which is one SCC, then we can print the SCC including the head.
  • We will consider only the tree edges and back edges while traversing, we ignore the cross edges as it separates one SCC from another.

So now, let us look how to implement the above steps. We are going to assign each node a time value for when it is visited or discovered. At root or start node Time value is 0. For every node in the graph, we assign a tuple with two time values: Disc and Low.

Disc: This indicates the time for when a particular node is discovered or visited during DFS traversal. For each node we increase the Disc time value by 1.

Low: This indicates the node with lowest discovery time accessible from a given node. If there is a back edge then we update the low value based on some conditions. The maximum value Low for a node can be assigned is equal to the Disc value of that node since the minimum discovery time for a node is the time to visit/discover itself.

Note: The Disc value once assigned will not change while we keep on updating the low value traversing each node. We will discuss the condition next.

Implementation in Java

Step 1:

We use a Map (Hash-Map) to store the graph nodes and edges. The Key of map stores the nodes and in the value we have a list which represents the edges from that node. For the Disc and Low we use two integer arrays of size same as a number of vertices. We fill both the arrays with -1, to indicate no nodes are visited initially. We use a Stack (for DFS) and a Boolean array inStack to check whether an already discovered node is present in our Stack in O(1) time as checking in the stack will be a costly operation (O(n)).

Step 2:

So, for each node we process we add it into our stack and mark true in the array inStack. We maintain a static Timer variable initialized to 0. If for an edge (u,v) if v node is already present in stack, then it is a back edge and (u,v) pair is Strongly Connected.  So we change the low value as :

if(Back-Edge) then Low[u] = Min ( Low[u] , Disc[v] ).

After visiting this node on returning the call to its parent node we will update the Low value for each node to ensure that Low value remains the same for all nodes in the Strongly Connected Component.

Step 3:

Now if for an edge (u,v) if v node is not present in stack then it is a tree edge or a neighboring edge. In such case, we update the low value for that particular node as :

if (Tree-Edge) then Low[u] = Min ( Low[u] , Low[v] ).

We determine the head or start node of each SCC when we get a node whose Disc[u] = Low[u], such a node is the head node of that SCC. Every SCC should have such a node maintaining this condition. After this, we just print the nodes by popping them out of the stack marking the inStack as false for each popped value.

Note: A Strongly Connected Component must have all its low values same. We will print the nodes in reverse order.

Now, let us look at the code for this in Java:

import java.util.*;
public class File
{
   
  static HashMap<Integer,List<Integer>> adj=new HashMap<>();
  static int Disc[]=new int[8];
  static int Low[]=new int[8];
  static boolean inStack[]=new boolean[8];
  static Stack<Integer> stack=new Stack<>();
  static int time = 0;
  
  static void DFS(int u)
  {
        
        Disc[u] = time;
        Low[u] = time;
        time++;
        stack.push(u);
        inStack[u] = true;
    List<Integer> temp=adj.get(u); // get the list of edges from the node.
    
    if(temp==null)
    return;
    
        for(int v: temp)
        {
                if(Disc[v]==-1) //If v is not visited
                {
                        DFS(v);
                        Low[u] = Math.min(Low[u],Low[v]);
                }
                //Differentiate back-edge and cross-edge
                else if(inStack[v])     //Back-edge case
                        Low[u] = Math.min(Low[u],Disc[v]);
        }

        if(Low[u]==Disc[u])     //If u is head node of SCC
        {
                System.out.print("SCC is: ");
                while(stack.peek()!=u)
                {
                        System.out.print(stack.peek()+" ");
                        inStack[stack.peek()] = false;
                        stack.pop();
                }
                System.out.println(stack.peek());
                inStack[stack.peek()] = false;
                stack.pop();
        }
  }

static void findSCCs_Tarjan(int n)
  {
        
    for(int i=1;i<=n;i++)
    {
        Disc[i]=-1;
        Low[i]=-1;
        inStack[i]=false;
    }
                

        for(int i=1;i<=n;++i)
        {
                if(Disc[i]==-1)
                        DFS(i);   // call DFS for each undiscovered node.
        }
  }

  public static void main(String args[])
  {
    adj.put(1,new ArrayList<Integer>());
    adj.get(1).add(3);
    
    adj.put(2,new ArrayList<Integer>());
    adj.get(2).add(1);
        
        adj.put(3,new ArrayList<Integer>());
        adj.get(3).add(2);
        adj.get(3).add(4);

        adj.put(4,new ArrayList<Integer>());
        adj.get(4).add(5);
        
        adj.put(5,new ArrayList<Integer>());
        adj.get(5).add(6);
        
        adj.put(6,new ArrayList<Integer>());
        adj.get(6).add(7);
        
        adj.put(7,new ArrayList<Integer>());
        adj.get(7).add(4);

        findSCCs_Tarjan(7);
  }

}

Output:

SCC is: 7 6 5 4
SCC is: 2 3 1

The code is written for the same example as discussed above, you can see the output showing the Strongly Connected Components in reverse order since we use a Stack. Now let us look at the complexities of our approach.

Time Complexity: We are basically doing a Single DFS Traversal of the graph so time complexity will be O( V+E ). Here, V is the number of vertices in the graph and E is the number of edges.

Space Complexity: We at the most store the total vertices in the graph in our map, stack, and arrays. So, the overall complexity is O(V).

So that’s it for the article you can try out different examples and execute the code in your Java Compiler for better understanding.

Let us know any suggestions or doubts regarding the article in the comment section below.

The post Tarjan’s Algorithm with Implementation in Java appeared first on The Crazy Programmer.



from The Crazy Programmer https://ift.tt/3vYOXew

Client-server architecture is a network model where every process or computer on a network is a server or a client. The client-servers are the robust computers that are dedicated to managing the printers, disk drives, and network traffic. Clients are workstations or PCs on which the users run their applications. Clients mainly rely on the servers for resources, like devices, files, and processing power.

What is Client-Server Architecture?

A client-server architecture or model is an application network separating tasks between the clients and servers that live in the same system or have to communicate through a computer network. The server-client mainly relies on sending the request to another program to access the service made accessible by the server. This server runs a few programs that share the resources with & distribute work among the clients.

A client-server relationship corresponds to the request–response pattern and should adhere to the common communications procedure that defines the language, rules, or dialog patterns used. The client-server communication adheres to TCP or IP protocol suite.

The TCP protocol maintains the connection until a client/server has completed their message exchange. And TCP protocol decides the best method to distribute the application data in packets that networks will deliver, transfers the packets to and get packets from a network, and manages the flow control or retransmission of the dropped and garbled packets. Internet Protocol is the connectionless protocol where every packet traveling on the Internet is the independent data unrelated to other data units.

How Does Client-Server Architecture Works?

client server architecture diagram

Now let us go ahead and look at how the Internet works through web browsers.

Client: The word Client means an organization or an individual using a service. Even in the digital world Client is a Host (computer) that can receive information or using service from the Servers.

Server: Server means a person that serves something. The server, in the digital world, is the remote computer that offers information or access to services.

So, it is basically a Client requesting something & a Server serving it providing its presence in a database.

Types of Client-Server Architecture

1-Tier Architecture

1-Tier Architecture

Image Source

All client or server configuration settings, UI environment, data logic, as well as marketing logic are there on the same system. The 1-tier architecture services are quite reliable but tough tasks to handle as they have all data in various variance that will be allotted the complete replication of the whole work. 1-Tier architecture also has different layers.

For example –Business, Presentation, Data Access layer using a single software package. Data will be saved on a local machine. Some applications manage 3 tiers like an MP3 player and MS Office; however, these applications are presented in a 1-tier architecture system.

2-Tier Architecture

2-Tier Architecture

Image Source

In 2-Tier Architecture, the UI is stored at the client machine, and the database gets stored on a server. The business logic and database logic are filed at server or client but have to be well-maintained. Suppose Data Logic and Business Logic are collected at the client-side, it’s called fat client-server architecture. Suppose Data Logic and Business Logic are handled on a server, its thin client-server architecture. It is considered affordable.

In 2-Tier architecture, server and client need to come in the direct incorporation. Suppose a client provides any input to a server there must not be any intermediate. It is generally done for rapid results and to avoid confusion between various clients. For example, an online ticket reservations application uses this 2-Tier architecture.

3-Tier Architecture

3-Tier Architecture

Image Source

It consists of the presentation tier that is the User Interface layer, an application tier that is a service layer, which performs the detailed processing, and a data tier that consists of the database server, which stores information. Three-tier architecture can be split into 3 parts, the presentation layer (or Client Tier), the Application layer (or Business Tier), and the Database layer (or Data Tier). It works in the following ways: The Client system handles the Presentation layer; the Application server looks after the Application layer, and the Server system supervises the Database layer.

N-Tier Architecture

N-Tier or Multi Tier Architecture

Image Source

Last but not the least, N-Tier architecture is known as a “Multitier Architecture”, hence its scaled form of the 3-tier architecture. The whole presentations, app processing, and even data management features are isolated from one another in this architecture.

Advantages of Client-Server Architecture

  • Cost-efficient needs less maintenance cost & Data recovery is made possible.
  • The capacity of the Client/Servers will be changed separately.
  • Centralized system with data in one single place.

Disadvantages of Client-Server Architecture:

  • Clients can be prone to viruses, worms, and Trojans if present in a Server/uploaded in the Server.
  • The server can be prone to Denial of Service attacks.
  • Data packets will be modified or spoofed during the transmission.
  • Phishing and capturing login credentials and other useful info of user are quite common and Man in a Middle attack will be common.

Examples of Client-Server Architecture

There’re different examples of the client-server model in daily life. Given are a few client-server examples-

  • Mail Servers: Email servers can be used for sending & receiving emails. Different software allows email handling.
  • File Servers: They are the centralized location for the files. For example, cloud services for Microsoft Office and Google docs will be accessed from your devices, and files that you save from the computer will be accessed from your phone. In this way, file stores will be centralized and accessed by multiple clients.
  • Web Servers: These servers will host different websites and these are high-performance computers where websites get hosted. The client is using, and the web server is a server system, which hosts these websites. The user or client requests resources or server’s site data through high-speed internet.

Final Words

In the client-model computing, the centralized communications server, the model is a central node, which communicates with client nodes. The major benefit that the client and server relationship has on the P2P peer relationship is the ability of handling data and apps on a centralized server.

The post Client-Server Architecture – Definition, Types, Examples, Advantages & Disadvantages appeared first on The Crazy Programmer.



from The Crazy Programmer https://ift.tt/3lFichG

Landing a job at Google is like a daydream come true!

Googlers around the world are highly satisfied with the culture, work-life balance, perks, and benefits that Google offers. However, it’s not easy for anyone to get a job at Google. 

Google ranks second in the world’s top four most valuable brands with Amazon (#1), Apple (#3), and Microsoft (#4). Being on the list of most valuable and top brands globally, you can assume how Google and Googlers work.

Google is the most used search engine that has answers for almost every queries people search. To make it more relevant, useful, and convenient, Google always tries to develop and magnify its platform on a global basis. And for that, the company requires a lot of creative, intelligent, and tech-savvy personalities who don’t just believe in hard-working; instead, a more creative and innovative approach that proves to be more productive and prolific for Googlers’ environment.

If you are from a technical background, you must have ever thought of how to get a job in Google India, right! To make it clear, Google doesn’t just offer vacancies only for technical candidates but also for design, business, Human Resources, and other backgrounds required for Google to operate. 

Nevertheless, the core functioning area of Google is technical, so most of the opportunities will always be for people from a technical background. 

Under its parent company, Alphabet, Google has its presence in around 50 countries with 85 office locations. To sum up, Google houses approximately 1,35,000 full-time employees, and the numbers will keep increasing with the continual development and inflation rate of Google. 

Here’s a catch!

Google has four branches in India in Tier 1 cities, including Mumbai, Bangaluru, Hyderabad, and Gurugram. Google India consists of more than 5,000 employees, and with the growing market in India, it is expected that Google will diversify its business across the whole country. Developers, tech-savvy people, business managers, and other innovative people can make their way in Google India.

So, are you excited to learn why and how to make your path to 

How to Get a Job in Google India?

Google Recruitment Process

Here, in this article, we’ll take you on the complete roller-coaster ride of why one should get a job in Google, Perks, and benefits, and how to land a job in Google. 

Google is one of the world’s highest-paid search engine and internet-related service providers. Google is an employer with equal benefits and assures the work culture, respectively. 

Also Read: How to become a Software Engineer in India?

Also Read: Software Engineer Salary in India

Types of Jobs at Google

Google primarly offer jobs in three key functional areas:

Technical: These are jobs related to software, coding, cloud-based, and other specialized jobs. A person with an exceptional technological background and offbeat skills can get a job a Google.

Business: This category comprises individuals who generate business for Google, such as Business Administrator, Marketing and Digital Marketing specialists, Human Resource, etc. 

Design: Professionals working in the Graphic Designing field, UI/UX writer, visual experts, etc., can also land a job at Google.

Try to be a Googler!

Have you ever wondered why Google is a dream company for most working professionals?

That’s because they don’t follow the rules!

Google promotes its employees to work in a free environment with all the benefits and perks that a typical working professional can only dream of. It offers complete flexibility to its employees to work more creatively. 

However, to access these benefits, you also need to be a person who thinks out of the box. Google recognizes its employees as Googlers and not just working people. Whenever Google is hiring people, they try to identify if you can become a Googler. 

Keynote: Google values creativity when it comes to recruiting rather than specific guidelines for recruitment.  

Perks and Benefits at Google

  • Free food
  • Insurance and mediclaim
  • On-site child care
  • Gym with instructors
  • Paid paternity and maternity leaves
  • Free health checks
  • Massage facility
  • Cab pickup and drop
  • Yoga classes
  • Video Games
  • Help with Financial planning
  • On-site physician
  • and a long list of other perks

Recruiting Process at Google

Google has created an incredible page on their hiring process to help you understand how Google hires Googlers. 

The company also claims that their hiring process is an integral part of its culture. They also believe that making a workplace more inclusive and representative starts with hiring. Besides, the process can be pervasive and time-consuming, but Google wants candidates to understand the company and analyze their skills by implementing a fair hiring process.

Recommended Tips Before Applying for a Job at Google

  • Google focuses more on individuality than the academic background of candidates. So, consider showcasing your skills, achievements learning, triumphs as well as failures while applying for a job.
  • Google believes it’s not always about achievements; it’s about how you overcome failures, breakdowns, and defeats. Undoubtedly, the comeback is always stronger than the setback. Don’t hesitate to reveal your failure, instead showcase how you surmount those. 
  • A minimum of a bachelor’s degree is what Google regards for, and you don’t need a master’s degree to prove your skills and work experience.
  • Try to build your resume with as many diverse experiences as you have gained in your work history because Google promotes people with diversified experience. 
  • Visualize your skills, experiences, interests, and goals, as Google promoted a work culture where people can also fulfill their hobbies.
  • Landing a job at Google is not easy, but also not impossible for those who think the same way as Googlers. There are a lot of videos on YouTube and documentation that can help you understand the work culture at Google. 
  • Describe the situations where you learned something that made everything come easier after. Remember, Google evaluates individuals based on their work history and the potential to do something. 
  • Work on small details such as how you solve complex problems, your contribution in the team effort, dealing with people, etc., which will make you stand out of the crowd.

Things to Keep in Mind Before Applying for a Job at Google

  • The resume must not be over 2 MB.
  • Education, work history, and cover letter are all optional.
  • You can make changes to an application before submitting it, including loading a different resume, but you can’t make changes after you submit it.
  • You must wait 90 days before reapplying for the same job. However, we find that candidates reapplying for technical roles are most successful when they’ve added 12 – 18 months more experience.
  • You can apply to up to three jobs within a rolling 30-day window. Focus on applying to jobs that are the most suitable match for your talents by carefully reading the overview and qualification information. See My Applications to review the jobs you’ve already applied for.

How to Apply for a Job in Google?

There are many ways to apply for a job at Google: 

Online Applications

Apply online for a vacancy that suits your profile on Google Careers. Based on your location, profile, and expertise, Google will filter out the jobs, or you can do it manually. All you have to do is fill in your details and apply. 

Campus Placements

Google also visit a few campuses across India, including IIM, NID, NIT, etc. If you’re the privileged one studying in any of these tier-1 colleges, you have the opportunity to impress recruiters.

Employee Referrals

You will do it to get your foot inside and quickly watch your submission if you have someone working at Google. You can also connect to employees through LinkedIn and ask for a job. Google recruiters are active on LinkedIn, and they might call you for an interview if your resume is impressive.

Google Workshops

Google organizes a coding event, Kick Start, in the Asia-Pacific region (APAC) every year for programmers. The interested candidates may register for the event and access any round of three hours they choose. Top competitors will get an interview on Google for a professional career.

The Further Process!

Once you’re done with applying for a job at Google and if your profile is shortlisted, typically, it takes a long four to six weeks to undergo the entire process. 

Undoubtedly, Google’s hiring process is very selective and thorough, which can take a lot of time, but eventually, Google tries to give candidates time to understand the company and even for themselves to know in-depth about them. 

You don’t have to fear for the same; instead, it’s the best way to concede, and Googlers will make your journey comfortable and pleasant throughout the process.

The best part!

Recruiters concentrate more on the applicant than the application, so you could hear about a position you didn’t initially apply for if they think you’re the best fit for a role.

If you have a tech job or a marketing job, a stage or a leadership position, you can see the same fundamentals as the method may slightly vary with different tasks or teams. These may not all relate to your position, but here are some ways Google evaluates applicants for employment:

  • Online Assessments
  • Short Virtual Chats
  • Project Work
  • In-depth Interviews
    • Structured Interview
    • Open-ended Interview

If you pass all the assessments, tests, and interview rounds, you reach the final stage of ‘Decision and Offer’ from Google.

The Final Spotlight!

One of the Google recruiters will reach out to you with an offer letter if they find you the most suitable candidate for the role. Upon taking this bid, the Google Onboarding Team will lead you on your way to becoming a Googler through compensation, incentives, badges, insurance, and so on.

Google Hiring Process | Video Demonstration

Prepare for your Google Interview | Video Demonstration

 

Google Interview Questions

  1. Which is your favorite programming language, and what do you not like about it?
  2. Tell me everything you know about hash tables.
  3. How does Traceroute network diagnostic tool work?
  4. How would you create an algorithm to verify whether a number is prime or not?
  5. Imagine you were creating a search engine for events; how would you go about it?
  6. Explain Linux virtual memory.
  7.  What kind of software are you interested in developing?
  8. Describe how Dijkstra’s algorithm works.
  9. How would you build a product like YouTube?
  10. What was the hardest bug to solve in a project that you worked on?
  11. How would you implement a thread-safe LRU cache?
  12. How would you find the longest substring which contains only two unique characters?
  13. How would you increase Google’s revenues?
  14. How would you handle a request from your boss that clearly violates company policy?
  15. Which traits differentiate a manager from a leader? How do you rank yourself on each?
  16. Tell me about a situation when you had to use your analytical skills.
  17. How would you prioritize a large book of clients in a short amount of time?
  18. How would you launch a product like a local search? What are the considerations and risks? How would you elicit the support of partners? How would you check for fraud?
  19. Why do you want to work for Google?
  20. Why are you a good fit for the role?
  21. How would you describe yourself?
  22. What’s your biggest achievement to date?
  23. What is your favorite Google product, and how would you improve it?
  24. What would you do if your coworker was constantly rude to her client on the phone?
  25. When you type www.google.com on your browser, what happens?
  26. How do you handle feedback?
  27. Do you have any suggestions for our products?

Frequently Asked Question and Answers by Google

Does Google still ask brainteasers in job interviews?

Based on research and their database, Google claims that brainteaser questions didn’t predict how well someone would do on the job, so they no longer ask them. Instead, they prefer work sample tests and ask structured interview questions.

Do I need a Computer Science degree to be a Google Software Engineer?

No, a Computer Science degree is not mandatory, as most of their software engineering or product manager roles.

Can I apply for multiple jobs?

Yes, you can apply for more than one role at once, though Google recommends narrowing your choices down to a few jobs that truly match your skills, experience, and interests. Google will review your resume/CV and transcript for interns and new graduates, determining the best fit. (Note: You can apply to three jobs within a rolling 30-day window.)

I’m a veteran — is there anything for me at Google?

Veterans are welcome and encouraged to apply to Google, learn more about our initiatives, roles, and programs on our dedicated veterans’ page.

What are the application deadlines?

Google job descriptions will include any application deadlines. Google accepts applications on a rolling basis for most openings and encourages you to apply sooner rather than later.

I interviewed/applied last year and wasn’t selected. May I reapply?

Yes, but Google asks that candidates must wait a year for engineering roles to gain additional experience before reapplying.

What technical classes should I take to prepare for technical interviews?

With a strong understanding of computer science, a broad, interdisciplinary background is the key to any job in software engineering at Google or elsewhere. Refer Guide to Technical Development by Google that offers resources to help you develop your technical skills.

Some roles have salary information, and some don’t. Why?

Google provides some salary information for roles in Colorado to be compliant with local legislation. The salary listed in the job description reflects the minimum for this particular role in Colorado and not for any other locations.

The Final Takeaway!

This article covers a piece of broad information on how to get a job in Google India and the recruitment process that Google follows. Google will now take a lot of expertise to apply for a job; if you have it, apply to the dream career. However, if you have vacant spaces in your curriculum vitae, apply for internships and find a place.

Please share your valuable comments and feedback in the comment section below and let us know if you find this piece of content helpful.

Cheers to Google!

The post How to Get a Job in Google India? appeared first on The Crazy Programmer.



from The Crazy Programmer https://ift.tt/2QgqHUU

In this article, we will look at yet another interesting problem popular in coding interviews. The problem states that Given a String we have to Find the Longest Palindromic Subsequence present in the String. We need to find only the Length of such subsequence. We will discuss various approaches related to our problem and analyze the time and space complexities.

By Subsequence, we mean a sequence of string characters not necessarily contiguous but they have to preserve their relative ordering. For Example, for the String : ABBHJ, AHJ is a subsequence of the string, because characters follow the order and each of them are present in the String. Now, we need to find a Palindromic Subsequence. E.g. For String, CBAFAB, BAAB and BAFAB are subsequences of the string and are palindrome. But Subsequence BAFAB is the longest among them with length 5.

Note: If a sequence of characters is contiguous it is a Substring. A substring is also a Subsequence.

Let us look at different approaches to solve this problem.

Approach 1 (Recursive Approach)

The Key steps to implement in this approach are:

  • We have two pointers: Left Pointer: Contains start index of string, Right Pointer: Contains last index end of string. We first check if the given string is of length 1 i.e. if value of left and right are same we return 1 as a single character string is palindrome.
  • Now, If the first character and the last character of the string matches, we add two to our result and recursively call for left+1 and right-1 index of the string.
  • If the characters at left and right index do not match then we search for a palindromic string between indexes (left+1, right) and (left, right-1) of the string, we consider the length obtained from the maximum of the two for each recursive call and keep on adding them to the result until we reach the base case.
Input : DABCFCBAG
Output : 7           // Here ABCFCBA IS Longest Palindromic Subsequence

Let us look at the code in Java:

class LongestPalindrome 
{ 
    // Returns the length of the Longest palindromic subsequence 
  
    static int longestPalindromeRecursive(String str, int left, int right) 
    { 
        // Boundary Check.
        if (left > right) { 
            return 0; 
        } 
        
        //If there is only 1 character or left = right.
        if(left == right)
        return 1;
  
        // If the characters at left and right index do match.  
        if (str.charAt(left) == str.charAt(right) ) 
        { 
            return 2 + longestPalindromeRecursive(str,left+1,right-1); 
        } 
  
  
        // If the first and last characters do not match  
        return Math.max(longestPalindromeRecursive(str, left, right - 1), longestPalindromeRecursive(str, left + 1, right)); 
    } 
  
    public static void main(String[] args) { 
        String str = "CBAFAB"; 
        int n = str.length(); 
        int result= longestPalindromeRecursive(str, 0, n - 1);
        System.out.print("The Length of the Longest Palindrome is: "+result); 
  
    } 
}

Output:

The Length of the Longest Palindrome is: 5

Time Complexity: We break each problem into 2 more sub problems in every recursive call. The time complexity is exponential in this case leading to O (2) complexity.

Approach 2 (Dynamic Programming)

We apply Dynamic Programming on Overlapping Subproblems. If there are problems which are computed again and again we can apply dynamic programming by storing results of previously occurred subproblems. This is the first property, the other one is Optimal Substructure, the problems whose final solution can be achieved by results of their subproblems. We see, both properties are evident in the recursive solution discussed above. So we apply Dynamic Programming. There are two approaches to discuss :

Top to Bottom Approach

In this approach we basically store the result of recursive solutions of each subproblem in a 2D Array for overlapping subproblems, to avoid repeated computations.

Let us look at the implementation of this approach in Java:

class LongestPalindrome 
{ 
    // Returns the length of the Longest palindromic subsequence 
  
    public static int longestPalindromeTop_To_Bottom(String str, int left, int right, Integer[][] arr) 
    {
    //Boundary check
    if(left > right)
      return 0;
    
    if(left == right) {
      return 1;
    }
    
    if(arr[left][right] == null) 
    {
      if(str.charAt(left) == str.charAt(right)) 
      {
        arr[left][right] = 2 + longestPalindromeTop_To_Bottom(str, left + 1, right - 1, arr);
      } 
      else 
      {
        arr[left][right] = Math.max(longestPalindromeTop_To_Bottom(str, left + 1, right, arr), longestPalindromeTop_To_Bottom(str, left, right - 1, arr));  
      }  
    }

    return arr[left][right];
  }
  
    public static void main(String[] args) 
    { 
        String str = "CABEEBAF"; 
        int n = str.length(); 
        
        Integer arr[][]=new Integer[n][n];
        int result= longestPalindromeTop_To_Bottom(str, 0, n - 1, arr);
        
        System.out.print("The Length of the Longest Palindrome is: "+result); 
  
    } 
}

Output:

The Length of the Longest Palindrome is: 6

Explanation: We use a 2D array to store the results obtained for each recursive call. We use Wrapper Class Integer array not primitive type because primitive type integer array initializes elements to zero. So to avoid confusion with our result which for some cases might give 0 we use it and Integer type array are initialized to null. So we check for the string with index left and right if the solution is not present in our array we recursively compute it (Like Previous Solution) and store it in our array. If the result is already computed we just return the result at index left and right. In such a case, there is no need of computing the same problem.

Time Complexity: The Time Complexity of this solution is O (n2), as we skip computing solutions of overlapping subproblems, we just return the already existing value.  The complexity is not exponential in this case.

Space Complexity: We use a 2D array of size equal to length of the string, n so overall complexity is O(n2).

Bottom Up Approach

In this approach we will first solve the basic bottom solutions or base cases first, then we find the actual solution of subproblems and the whole problem. Here, we check each combination and get the maximum palindromic length. For each subsequence, we check how many palindromic subsequences are possible with it and get its maximum length. We can start from the start or end of the string.

This is an iterative approach, we fill the 2D array from the right diagonal half. Here, we fill the diagonal elements as 1 because a single character is a palindrome of length 1. So, apart from the diagonal elements if the left and right characters do not match then:  Arr [left] [right]=Max( Arr[left+1] [right], Arr[left] [right-1] ).

If characters match then Arr[left][right]= 2+ Arr[left+1][right-1].

So, for the String ABEFBAC, The 2D array or tabulation look like this:

Longest Palindromic Subsequence

Note: We fill the table from the bottom and the max length is present at Arr[0] [n-1].

So let us have a look at the implementation of the above in Java:

class LongestPalindrome 
{ 
    // Returns the length of the Longest palindromic subsequence 
  
    public static int longestPalindromeBottomUp(String str, int n) 
    {
        
    int[][] arr = new int[n][n];
    // Initialize diagonal elements as 1.
    for (int i = 0; i < str.length(); i++) 
    {
      arr[i][i] = 1;
    }
      
    for(int left = n - 2; left >= 0; left--) 
    {
      for(int right = left + 1; right < n; right++) 
      {
        
        if(str.charAt(left) == str.charAt(right)) 
        {
          arr[left][right] = 2 + arr[left + 1][right - 1];
        } 
        else 
        {
          arr[left][right] = Math.max(arr[left + 1][right], arr[left][right - 1]);
        }
      }
    }
    // return the max length.
    return arr[0][n - 1];
  }
    public static void main(String[] args) 
    { 
        String str = "ABEFBAC"; 
        int n = str.length(); 
        
        int result= longestPalindromeBottomUp(str, n);
        
        System.out.print("The Length of the Longest Palindrome is: "+result); 
  
    } 
}

Output:

The Length of the Longest Palindrome is: 5

Time Complexity: The complexity is O (n2) as above it is still effective being an iterative approach.

Space Complexity: It is O (n2), as we use a 2D array for the tabulation shown above.

So that’s it for the article you can try out the problem with different examples to test your understanding and execute the code too in your local compiler.

Feel free to leave suggestions or doubts (if any) in the comments section below.

The post Longest Palindromic Subsequence in Java appeared first on The Crazy Programmer.



from The Crazy Programmer https://ift.tt/3c2ccMN

MKRdezign

Contact Form

Name

Email *

Message *

Powered by Blogger.
Javascript DisablePlease Enable Javascript To See All Widget