Posts

Showing posts from May, 2020

Odd Even Linked List

Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes. You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity. Example 1: Input: 1->2->3->4->5->NULL Output: 1->3->5->2->4->NULL Example 2: Input: 2 ->1->3->5->6->4->7->NULL Output: 2->3->6->7->1->5->4->NULL Note: The relative order inside both the even and odd groups should remain as it was in the input. The first node is considered odd, the second node even and so on ...   /**  * Definition for singly-linked list.  * public class ListNode {  *     int val;  *     ListNode next;  *     ListNode() {}  *     ListNode(int val) { this.val = val; }  *...

Maximum Sum Circular Subarray

Given a circular array   C of integers represented by  A , find the maximum possible sum of a non-empty subarray of C . Here, a  circular array means the end of the array connects to the beginning of the array.  (Formally, C[i] = A[i] when 0 <= i < A.length , and C[i+A.length] = C[i]  when  i >= 0 .) Also, a subarray may only include each element of the fixed buffer A at most once.  (Formally, for a subarray C[i], C[i+1], ..., C[j] , there does not exist i <= k1, k2 <= j with k1 % A.length = k2 % A.length .)   Example 1: Input: [1,-2,3,-2] Output: 3 Explanation: Subarray [3] has maximum sum 3 Example 2: Input: [5,-3,5] Output: 10 Explanation:   Subarray [5,5] has maximum sum 5 + 5 = 10 Example 3: Input: [3,-1,2,-1] Output: 4 Explanation:   Subarray [2,-1,3] has maximum sum 2 + (-1) + 3 = 4 Example 4: Input: [3,-2,2,-3] Output: 3 Explanation:   Subarray [3] and [3,-2...

Implement Trie (Prefix Tree)

Implement a trie with insert , search , and startsWith methods. Example: Trie trie = new Trie(); trie.insert("apple"); trie.search("apple"); // returns true trie.search("app"); // returns false trie.startsWith("app"); // returns true trie.insert("app"); trie.search("app"); // returns true Note: You may assume that all inputs are consist of lowercase letters a-z . All inputs are guaranteed to be non-empty strings.   class TrieNode {         private TrieNode[] nodeLinks;     public boolean isEnd;     public TrieNode() {         nodeLinks = new TrieNode[26];     }     public boolean containsKey(char ch) {         return nodeLinks[ch -'a'] != null;     }     public TrieNode get(char ch) {         return nodeLinks[ch -'a'];  ...

Remove K Digits

Given a non-negative integer num represented as a string, remove k digits from the number so that the new number is the smallest possible. Note: The length of num is less than 10002 and will be ≥ k . The given num does not contain any leading zero. Example 1: Input: num = "1432219", k = 3 Output: "1219" Explanation: Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest. Example 2: Input: num = "10200", k = 1 Output: "200" Explanation: Remove the leading 1 and the number is 200. Note that the output must not contain leading zeroes. Example 3: Input: num = "10", k = 2 Output: "0" Explanation: Remove all the digits from the number and it is left with nothing which is 0.   class Solution {     public String removeKdigits(String num, int k) {         for (int i = 1; i <= k; i++)             num = toRemoveOneDigit(num);     ...

Single Element in Sorted Array

You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once. Find this single element that appears only once. Example 1: Input: [1,1,2,3,3,4,4,8,8] Output: 2 Example 2: Input: [3,3,7,7,10,11,11] Output: 10 Note: Your solution should run in O(log n) time and O(1) space. METHOD 1:   class Solution {     public int singleNonDuplicate(int[] nums) {         int result = 0;         for(int num:nums)             result ^= num;         return result;     } } Try it on Leetcode Here we are going to do XOR operation. Because, in the problem itself they mentioned that each number in array repeated twice and only one number occurs once. Also XOR of same number is 0 and i...

Flood Fill

An image is represented by a 2-D array of integers, each integer representing the pixel value of the image (from 0 to 65535). Given a coordinate (sr, sc) representing the starting pixel (row and column) of the flood fill, and a pixel value newColor , "flood fill" the image. To perform a "flood fill", consider the starting pixel, plus any pixels connected 4-directionally to the starting pixel of the same color as the starting pixel, plus any pixels connected 4-directionally to those pixels (also with the same color as the starting pixel), and so on. Replace the color of all of the aforementioned pixels with the newColor. At the end, return the modified image. Example 1: Input: image = [[1,1,1],[1,1,0],[1,0,1]] sr = 1, sc = 1, newColor = 2 Output: [[2,2,2],[2,2,0],[2,0,1]] Explanation: From the center of the image (with position (sr, sc) = (1, 1)), all pixels connected by a path of the same color as the starting pixel are colored with the new color. ...

Find the Town Judge

In a town, there are N people labelled from  1 to N .  There is a rumor that one of these people is secretly the town judge. If the town judge exists, then: The town judge trusts nobody. Everybody (except for the town judge) trusts the town judge. There is exactly one person that satisfies properties 1 and 2. You are given trust , an array of pairs trust[i] = [a, b] representing that the person labelled a trusts the person labelled b . If the town judge exists and can be identified, return the label of the town judge.  Otherwise, return -1 .   Example 1: Input: N = 2 , trust = [[1,2]] Output: 2 Example 2: Input: N = 3 , trust = [[1,3],[2,3]] Output: 3 Example 3: Input: N = 3 , trust = [[1,3],[2,3],[3,1]] Output: -1 Example 4: Input: N = 3 , trust = [[1,2],[2,3]] Output: -1 Example 5: Input: N = 4 , trust = [[1,3],[1,4],[2,3],[2,4],[4,3]] Output: 3   Note: 1 <= N <= 1000 trust.length <= 10000 ...

Valid Perfect Square

Given a positive integer num , write a function which returns True if num is a perfect square else False. Note: Do not use any built-in library function such as sqrt . Example 1: Input: 16 Output: true Example 2: Input: 14 Output: false   class Solution {     public boolean isPerfectSquare(int num) {        for (long i = 1; i * i <= num; i++) {                if ((i)*(i) == num) {                 return true;             }         }         return false;             } } Try it on Leetcode Here, they mentioned in problem not to use in-build methods. We are going to use basic idea to solve this...

Check If It Is a Straight Line

Image
You are given an array  coordinates , coordinates[i] = [x, y] , where [x, y] represents the coordinate of a point. Check if these points make a straight line in the XY plane. Example 1: Input: coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]] Output: true Example 2: Input: coordinates = [[1,1],[2,2],[3,4],[4,5],[5,6],[7,7]] Output: false   Constraints: 2 <= coordinates.length <= 1000 coordinates[i].length == 2 -10^4 <= coordinates[i][0], coordinates[i][1] <= 10^4 coordinates  contains no duplicate point.   class Solution {     public boolean checkStraightLine(int[][] coordinates) {             double tSlope = 0;         int length = coordinates.length - 1, i;                  double slope = (double)(coordinates[1][1] - coordinates[0][1])...

Cousins in Binary Tree

Image
In a binary tree, the root node is at depth 0 , and children of each depth k node are at depth k+1 . Two nodes of a binary tree are cousins if they have the same depth, but have different parents . We are given the root of a binary tree with unique values, and the values x  and y  of two different nodes in the tree. Return  true  if and only if the nodes corresponding to the values x and y are cousins.   Example 1: Input: root = [1,2,3,4] , x = 4 , y = 3 Output: false Example 2: Input: root = [1,2,3,null,4,null,5] , x = 5 , y = 4 Output: true Example 3: Input: root = [1,2,3,null,4] , x = 2, y = 3 Output: false   Note: The number of nodes in the tree will be between 2 and 100 . Each node has a unique integer value from 1 to 100 .   /**  * Definition for a binary tree node.  * public class TreeNode {  *     int val;  *     TreeNode left;  *...

Online learning platform Unacademy hacked, details of 22 million users available for sale

Image
Unacademy, one of the largest online learning platforms in India has faced a data breach and details of 22 million users of Unacademy are reportedly available for sale now. According to security firm Cyble Inc, a hacker is offering the user database, containing 21,909,707 records, for USD 2,000. Cyble Inc added that it has managed to acquire the database and added the user records to its data breach monitoring service which can be used by millions of Unacademy users to determine whether their account was hacked or not. Unacademy, one of the largest online learning platforms in India has faced a data breach and details of 22 million users of Unacademy are reportedly available for sale now. According to security firm Cyble Inc, a hacker is offering the user database, containing 21,909,707 records, for USD 2,000. Cyble Inc added that it has managed to acquire the database and added the user records to its data breach monitoring service which can be used by millions of Unacad...

High paying coding languages you can learn for free

Image
For millions of people, COVID-19 quarantine and self-isolation is a great time to start learning and upskilling. Coding - which is considered to be one of the most in-demand skills in the year 2020 - is being taught by various institutes and platforms for free. Although the preset lockdown has literally locked everyone indoors, it has opened many ways and opportunities to learn and grow. We bring you five highly paid languages and online sources to learn these languages for free: Perl The salary earned by a Perl developer is about 54.2% higher than the global average salary, say industry reports. If you want to learn the basics of Perl, you can refer to Perl For Newbies . If you are new in the coding domain, try your hands on some more common coding languages like Java and Python. In case you have a basic understanding of Perl, you can refer to Tutorials Point and Learn Perl. Scala On an average, a Scala developer salary is 41.6% higher than the global average salary, esti...

Majority Element

Given an array of size n , find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times. You may assume that the array is non-empty and the majority element always exist in the array. Example 1: Input: [3,2,3] Output: 3 Example 2: Input: [2,2,1,1,1,2,2] Output: 2   class Solution { public int majorityElement(int[] nums) { Arrays.sort(nums); return nums[nums.length/2]; } } Here, we are sorting the entire array using sort() of Arrays class. Then, number at index position n/2 would be a majority element. There is no chance of wrong values in odd or even length.   Below is another method using HashMap. METHOD 2: class Solution { public int majorityElement(int[] nums) { HashMap<Integer, Integer>list = new HashMap<Integer, Integer>(); int ...

Twitter tests a warning message that tells users regarding offensive replies

Image
Twitter is experimenting with a new moderation tool that will warn users before they post replies that contain what the company says is “harmful” language. Twitter describes it as a limited experiment, and it’s only going to show up for iOS users. The prompt that is now supposed to pop up in certain situations will give “you the option to revise your reply before it’s published if it uses language that could be harmful,” reads a message from the official Twitter Support channel.  The approach isn’t a novel one. It’s been used by quite a few other social platforms before, most prominently Instagram. The Facebook-owned app now warns users before they post a caption with a message that says the caption “looks similar to others that have been reported.” Prior to that change, Instagram rolled out a warning system for comments last summer. It’s not exactly clear how Twitter is labeling harmful language, but the company does have hate speech policies and a broader Twitter Rul...

Google’s Stadia controller will finally work wirelessly with computers

Image
Google’s Stadia Controller will finally work wirelessly with laptops and desktops (but it doesn't work wirelessly with mobile phones) starting this week, the company announced today ( via Engadget ). Since the cloud gaming service’s November launch, the only way you could use your controller wirelessly was if you were playing Stadia on your TV with a Chromecast Ultra. You still can’t use the Stadia Controller wirelessly with an Android phone, though, and it’s not clear when that functionality might arrive. When used wirelessly, the Stadia controller connects to Google’s servers over Wi-Fi instead of connecting to the device in front of you over Bluetooth, like most other gaming controllers. Google says this helps the controller “deliver precise controls.” If you want to connect your Stadia controller wirelessly, you can follow Google’s support documentation here . If you want to pick up a Stadia controller, you can buy one for $69 or for $129 as part of the Stadia P...

First Unique Character in a String

Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1. Examples: s = "leetcode" return 0. s = "loveleetcode", return 2. Note: You may assume the string contain only lowercase letters. class Solution {     public int firstUniqChar(String s) {         int length = s.length();         String str;         for(int i=0;i<length;i++){             if(i==length-1){                 str = s.substring(0, i);             }             else{                 str = s.substring(0,i)+s.sub...

How to convert Float to String in Java?

ss In last post, we have learned how to convert string to float in java. In this post, we are going to learn how to convert float to string in Java. Consider the situation, if we want to display float value is any text area or if we want to do any manipulation using float value, conversion of float to string is need to be known. Conversion of float to string in java can be done in  following ways: toString(float f) It is a static method of float class. It provides a string representation of float value. If float value is NaN, then result in String is NaN. Else, it will provides string representation of float. For more detailed about this method. public static String toString(float f) Parameter   f - float value Returns a string representation of float value. valueOf() It is a static method of String class. It returns string representation of float argument. public static String valueOf(...

Number Complement

Image
Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation. Example 1: Input: 5 Output: 2 Explanation: The binary representation of 5 is 101  (no leading zero bits), and its complement is 010.  So you need to output 2. Example 2: Input: 1 Output: 0 Explanation: The binary representation of 1 is 1  (no leading zero bits), and its complement is 0.  So you need to output 0. Note: The given integer is guaranteed to fit within the range of a 32-bit signed integer. You could assume no leading zero bit in the integer’s binary representation. This question is the same as 1009:  https://leetcode.com/problems/complement-of-base-10-integer/ class Solution {     public int findComplement(int num) {                 int totalBits = (int)(Math.floor(Math.log(num) / Math.log(2))) + 1; ...

How to convert String to Float in Java?

In Java understanding of all data types conversion is helpful in many ways. In this post, we are going to learn how to covert string to float in java Consider the scenario, if you are receiving float value using text field or text area, the float value is stored in the form of string. Then at that place there is a need to convert string to float for further operations. parseFloat(String s) It is used to convert a float value stored in a string to a float variable. It is a static method of float class. public static float parseFloat(String s) throws NumberFormatException Parameters s - a string to be parsed Returns returns a float value Exception if a string cannot be parsed throws NumberFormatException valueOf(String s) It is also one of static method of float class. If string is null, throws NullPointer Exception public static float valueOf(String s) throws NumberFormatException Parameters s - a string to be parsed Returns returns a float val...

Ransom Note

Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom note can be constructed from the magazines ; otherwise, it will return false. Each letter in the magazine string can only be used once in your ransom note. Note: You may assume that both strings contain only lowercase letters. canConstruct("a", "b") -> false canConstruct("aa", "ab") -> false canConstruct("aa", "aab") -> true   class Solution { public boolean canConstruct(String ransomNote, String magazine) { StringBuilder sb = new StringBuilder(); sb.append(magazine); int length = ransomNote.length(), count = 0; for(int i=0;i<length;i++){ int index = sb.indexOf(ransomNote.charAt(i)+""); if(index != -1){ sb.delete(index, index+1); count++; ...

Jewels and Stones

Image
You're given strings J representing the types of stones that are jewels, and S representing the stones you have.  Each character in S is a type of stone you have.  You want to know how many of the stones you have are also jewels. The letters in J are guaranteed distinct, and all characters in J and S are letters. Letters are case sensitive, so "a" is considered a different type of stone from "A" . Example 1: Input: J = "aA", S = "aAAbbbb" Output: 3   Example 2: Input: J = "z", S = "ZZ" Output: 0   Note: S and J will consist of letters and have length at most 50. The characters in J are distinct. METHOD 1: class Solution {     public int numJewelsInStones(String J, String S) {        int res=0;        for(char c : S.toCharArray()){            if(J.indexOf(c) != -1){       ...

First Bad Version

You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad.   Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following ones to be bad. You are given an API bool isBadVersion(version) which will return whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API. Example: Given n = 5, and version = 4 is the first bad version. call isBadVersion(3) -> false call isBadVersion(5) -> true call isBadVersion(4) -> true Then 4 is the first bad version.      METHOD 1:     /* The isBadVersion API is defined in the parent class VersionControl. boolean isBadVersion(int version); */...