Class ArrayUtil

java.lang.Object
org.drip.service.common.ArrayUtil

public class ArrayUtil
extends java.lang.Object
ArrayUtil implements Generic Array Utility Functions used in DROP modules.



Author:
Lakshmi Krishnamurthy
  • Constructor Summary

    Constructors
    Constructor Description
    ArrayUtil()  
  • Method Summary

    Modifier and Type Method Description
    static java.util.List<int[]> ArrayPairList​(int[] numberArray, int x)
    Find all pairs of integers in the array which have difference equal to the number d.
    static boolean BalancedPartition​(int[] numberArray)
    Given an array containing only positive integers, return if you can pick two integers from the array which cuts the array into three pieces such that the sum of elements in all pieces is equal.
    static int BaseballScore​(java.lang.String[] scoreEventArray)
    Tom plays a game in which he throws a baseball at various blocks marked with a symbol.
    static int BODMAS​(java.lang.String s)
    Execute a BODMAS Evaluation of the Expression
    static boolean CanJumpToLastIndex​(int[] numberArray)
    Given an array of non-negative integers, you are initially positioned at the first index of the array.
    static java.util.List<java.lang.Boolean> CanMakePalindromeQueries​(java.lang.String s, int[][] queries)
    Given a string s, we make queries on substrings of s.
    static int CircularArrayLoop​(int[] numberArray)
    Determine if there is a loop (or a cycle) in numberArray.
    static int ClosestNextPrimeNumber​(int number)
    Given an integer n, return the smallest prime palindrome greater than or equal to n.
    static java.util.Collection<int[]> CollapseOverlappingRanges​(java.util.List<int[]> rangeList)
    Collapse any Overlapping Ranges inside the Specified List
    static boolean ContinuousSubarraySum​(int[] numberArray, int k)
    Given a list of non-negative numbers and a target integer k, check if the array has a continuous sub-array of size at least 2 that sums up to a multiple of k, that is, sums up to n*k where n is also an integer.
    static boolean ContinuousSubarraySumMod​(int[] numberArray, int k)
    Given an integer array and an integer k, return true if the array has a continuous sub-array of size at least two whose elements sum up to a multiple of k, or false otherwise.
    static boolean ConversionToNondecreasing​(int[] numberArray)
    Given an array of integers, your task is to check if it could become non-decreasing by modifying at most one element.
    static int[] CountSubArrays​(int[] arr)
    You are given an array a of N integers.
    static int CountWaysToSeparate​(java.lang.String numberStr)
    Count the Number of Ways to Separate the Number
    static int DiscountedSale​(int[] priceArray, java.util.List<java.lang.Integer> nonDiscountedItems)
    A shopkeeper has a sale to complete and has arranged the items being sold in a list.
    static int[] EnumerateDiagonalFlipFlop​(int[][] matrix)
    Given a matrix, return all elements of the matrix in diagonal flip-flop order.
    static java.util.List<java.util.List<java.lang.Integer>> EnumerateDiagonalOrder​(int[][] matrix)
    Given a matrix, return all elements of the matrix in anti-diagonal order.
    static java.util.List<java.lang.String> ExpressionOperatorPathList​(int[] numberArray, int target)
    Given a string that contains only digits 0-9 and a target value, return all possibilities to add binary operators (not unary) +, -, or * between the digits so they evaluate to the target value.
    static int[] FindSignatureCount​(int[] studentArray)
    There are n students, numbered from 1 to n, each with their own year-book.
    static int[] FirstAndLastPosition​(int[] numberArray, int target)
    Find the First and the Last Locations of the Target in the Array
    static int FirstMisingPositiveInteger​(int[] numberArray)
    Given an unsorted integer array, find the smallest missing positive integer.
    static java.util.Collection<java.util.List<java.lang.Integer>> FourSum​(int[] numberArray, int target)
    Given an array of n integers and an integer target, are there elements a, b, c, and d in the array such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.
    static int FourSumCount​(int[] numberArrayA, int[] numberArrayB, int[] numberArrayC, int[] numberArrayD)
    Given four lists A, B, C, D of integer values, compute how many tuples (i, j, k, l) there are such that A[i] + B[j] + C[k] + D[l] is zero.
    static java.util.Set<java.util.List<java.lang.Integer>> GeneratePathCombinations​(int[] numberArray, int target)
    Generate the Set of the Location Paths that meet the specified Target
    static java.util.TreeMap<java.lang.Integer,​int[]> GenerateSkyline​(java.util.TreeMap<java.lang.Integer,​int[]> skscraperMap)
    A city skyline is the outer contour of the silhouette formed by all the buildings in that city when viewed from a distance.
    static int IdentifyDuplicate​(int[] numberArray)
    Given an array containing n + 1 integers where each integer is between 1 and n (inclusive), assuming there is only one duplicate number, find the duplicate one.
    static boolean IncreasingTripletSubsequenceExists​(int[] numberArray)
    Given an unsorted array return whether an increasing subsequence of length 3 exists or not in the array.
    static java.util.List<int[]> InsertIntoNonOverlappingIntervals​(int[][] intervals, int[] newInterval)
    Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).
    static java.util.Collection<java.lang.String> InvalidTransactions​(java.lang.String[] transactionArray)
    A transaction is possibly invalid if: the amount exceeds $1000, or; if it occurs within (and including) 60 minutes of another transaction with the same name in a different city.
    static int InventoryProfit​(int[] inventoryArray, int orderCount)
    A company has several suppliers for its products.
    static int IslandCounter​(int[][] grid)
    Count the Number of Islands in the Grid
    static boolean JumpGameDestinationReachable​(java.lang.String s, int minJump, int maxJump)
    Indicate the Destination is Reachable
    static int[][] KClosestPoints​(int[][] pointGrid, int k)
    Extract the K-Closest Points
    static int KConcatenatedMaximumSum​(int[] numberArray, int k)
    Given an integer array arr and an integer k, modify the array by repeating it k times.
    static int KConcatenationMaximumSum​(int[] numberArray, int k)
    Given an integer array numberArray and an integer k, modify the array by repeating it k times.
    static int LargestRectangleInHistogram​(int[] heightArray)
    Given non-negative integers representing the histogram bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.
    static int[] LocationInSortedArray​(int[] numberArray, int target)
    Given an array of integers sorted in ascending order, find the starting and ending position of a given target value.
    static void main​(java.lang.String[] argumentArray)
    Entry Point
    static int MaxCutArea​(int h, int w, int[] horizontalCuts, int[] verticalCuts)
    Given a rectangular cake with height h and width w, and two arrays of integers horizontalCuts and verticalCuts where horizontalCuts[i] is the distance from the top of the rectangular cake to the ith horizontal cut and similarly, verticalCuts[j] is the distance from the left of the rectangular cake to the jth vertical cut.
    static int[] MaximumAreaUnderContainer​(int[] heightArray)
    Given non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai).
    static int MaximumAvailableDiskSpace​(int[] diskSpaceArray, int segmentLength)
    Company A is performing an analysis on the computers at one of its offices.
    static int MaximumNumberOfFamilies​(int n, int[][] reservedSeats)
    A cinema has n rows of seats, numbered from 1 to n and there are ten seats in each row, labeled from 1 to 10.
    static int MaximumPointsInLine​(int[][] points)
    Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane, return the maximum number of points that lie on the same straight line.
    static int MaximumProductSubarray​(int[] numberArray)
    Given an integer array, find the contiguous sub-array within an array (containing at least one number) which has the largest product.
    static int MaximumSubarraySum​(int[] numberArray)
    Compute the Maximum Sum of any Sub-array
    static double MaximumSubarraySumCircular​(int[] numberArray)
    Given a circular array C of integers represented by A, find the maximum possible sum of a non-empty sub-array of C.
    static int MaxPathScore​(int[][] matrix)
    Given a two 2D matrix, find the max score of a path from the upper left cell to bottom right cell that doesn't visit any of the cells twice.
    static double Median​(int[] numberArray)
    Evaluate the Array Median
    static double MedianOfSortedArrays​(int[] sortedArray1, int[] sortedArray2)
    There are two sorted arrays of size m and n respectively.
    static int[] MergeSortedArrays​(int[][] arrayOfArrays)
    Merge the Array of Sorted Arrays into a Single Array
    static int MinimumConsumptionRate​(int[] lotSizeArray, int totalTime)
    Calculate the Minimum Consumption Rate of the Array of Lot Sizes within the Total Time
    static int MinimumOverallAwkwardness​(int[] heightArray)
    There are n guests attending a dinner party, numbered from 1 to n.
    static int MinimumSubarraySum​(int[] numberArray)
    Compute the Minimum Sum of any Sub-array
    static boolean NearbyAlmostDuplicate​(int[] numberArray, int k, int t)
    Given an array of integers, find out whether there are two distinct indices i and j in the array such that the absolute difference between two numbers in it is at most t and the absolute difference between i and j is at most k.
    static int[] NextGreaterElement​(int[] numberArray)
    Given a circular array (the next element of the last element is the first element of the array), print the Next Greater Number for every element.
    static java.util.List<int[]> OptimizeMemoryUsage​(int[] foregroundTasks, int[] backgroundTasks, int k)
    Give a computer with total k memory space, and an array of foreground tasks and background tasks the computer needs to do.
    static int[] PancakeFlipSort​(int[] numberArray)
    Implement the Pancake Flip Sort
    static int PartitionArrayMinimizeSum​(int[] numberArray)
    You are given an integer array of 2 * n integers.
    static int PopulationInfection​(int[][] infectionMatrix)
    Given a 2D grid, each cell is either a zombie or a human.
    static int[] ProductOfArrayExceptSelf​(int[] numberArray)
    Compute the Array of Product of Array Except Self
    static int[] QueueReconstructionByHeight​(int[][] heightOrderArray)
    A Random list of people standing in a queue.
    static int RainWaterCatchmentArea​(int[] segmentHeightArray)
    Implement the Rain-water Catchment Area given the array of Heights
    static int[][] RandomMinesInGrid​(int m, int n, int k)
    Given a m-by-n grid, generate k mines on this grid randomly.
    static int ReachTargetMinimumJumps​(int[] forbiddenLocationArray, int a, int b, int target)
    A certain bug's home is on the x-axis at position x.
    static boolean ReverseMatchPossible​(int[] a, int[] b)
    Check if Reverse match is Possible
    static boolean SearchRotatedArray​(int[] numberArray, int target)
    Search for the Target in a Rotated Array
    static int SearchRotatedArray2​(int[] numberArray, int target)
    Search for the Target in a Rotated Array
    static boolean SetMatrixZeroes​(int[][] matrix)
    Given a m x n matrix, if an element is 0, set its entire row and column to 0.
    static int ShortestSubarrayAtLeastSum​(int[] numberArray, int sum)
    Given an integer array and an integer, return the length of the shortest non-empty subarray with a sum of at least sum.
    static java.util.TreeMap<java.lang.Integer,​java.lang.Integer> SliceOverlappingRanges​(java.util.List<int[]> rangeList)
    Generate a Counter Map of the Overlapping Slice Ranges
    static int[] SlidingWindowMaximum​(int[] numberArray, int k)
    Build the Array of Maximum Sliding Window of Size k
    static void SortColor​(int[] numberArray)
    Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue.
    static int SortedMatrixKthElement​(int[][] matrix, int k)
    Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in the matrix.
    static int SparseMatrixDotProduct​(int[][] matrix)
    Compute the Dot Product of the Sparse Matrix
    static java.util.Map<java.lang.String,​java.lang.Integer> SparseMatrixRepresentation​(int[][] matrix)
    Construct a Sparse Matrix Representation
    static java.util.List<java.lang.Integer> SpiralMatrixOrder​(int[][] matrix)
    Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
    static boolean SplitIntoSameAverage​(double[] numberArray)
    Check if the Array can be split so that the Two Sides add to the same
    static int StrategicBalloonBurstSum​(int[] balloonCoinArray)
    Given an array of balloons, each balloon is painted with a number on it represented by array.
    static int SubarrayMinimum​(int[] numberArray)
    Given an array of integers, find the sum of min(B), where B ranges over every (contiguous) sub-array.
    static java.util.List<java.lang.String> TargetApproachPathList​(int[] numberArray, int target)
    Given a list of integers and a target.
    static int TargetSum​(int[] numberArray, int target)
    Count the Number of Ways to reach the Target
    static java.util.Map<java.lang.String,​int[]> ThreeSum​(int[] numberArray)
    Given an array of n integers, find all unique triplets in the array which gives the sum of zero.
    static int UniqueElementsInSortedArray​(int[] numberArray)
    Count the Unique Elements in the Sorted Array
    static int UniquePathsWithObstacles​(int[][] obstacleGrid)
    A robot is located at the top-left corner of a m x n grid.
    static boolean WiggleSort​(int[] numberArray)
    Given an unsorted array numberArray, reorder it such that numberArray[0] le numberArray[1] ge numberArray[2] le numberArray[3]....
    static boolean WiggleSort2​(int[] numberArray)
    Implement the Wiggle Sort Version 2
    static boolean WordExistsInBoard​(char[][] board, java.lang.String word)
    Given a 2D board and a word, find if the word exists in the grid.

    Methods inherited from class java.lang.Object

    equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
  • Constructor Details

    • ArrayUtil

      public ArrayUtil()
  • Method Details

    • SearchRotatedArray

      public static final boolean SearchRotatedArray​(int[] numberArray, int target)
      Search for the Target in a Rotated Array
      Parameters:
      numberArray - The Rotated Number Array
      target - The Target
      Returns:
      TRUE - The Number exists
    • SearchRotatedArray2

      public static final int SearchRotatedArray2​(int[] numberArray, int target)
      Search for the Target in a Rotated Array
      Parameters:
      numberArray - The Rotated Number Array
      target - The Target
      Returns:
      TRUE - The Rotated Index
    • ThreeSum

      public static final java.util.Map<java.lang.String,​int[]> ThreeSum​(int[] numberArray)
      Given an array of n integers, find all unique triplets in the array which gives the sum of zero.
      Parameters:
      numberArray - The Number Array
      Returns:
      The List of Unique Triplets
    • CircularArrayLoop

      public static final int CircularArrayLoop​(int[] numberArray)
      Determine if there is a loop (or a cycle) in numberArray. A cycle must start and end at the same index and the cycle's length gt 1. Furthermore, movements in a cycle must all follow a single direction. In other words, a cycle must not consist of both forward and backward movements.
      Parameters:
      numberArray - The Number Array
      Returns:
      TRUE - The Circle has a Loop
    • MaxCutArea

      public static final int MaxCutArea​(int h, int w, int[] horizontalCuts, int[] verticalCuts)
      Given a rectangular cake with height h and width w, and two arrays of integers horizontalCuts and verticalCuts where horizontalCuts[i] is the distance from the top of the rectangular cake to the ith horizontal cut and similarly, verticalCuts[j] is the distance from the left of the rectangular cake to the jth vertical cut. Return the maximum area of a piece of cake after you cut at each horizontal and vertical position provided in the arrays horizontalCuts and verticalCuts.
      Parameters:
      h - Cake Height
      w - Cake Width
      horizontalCuts - Array of Horizontal Cuts
      verticalCuts - Array of Vertical Cuts
      Returns:
      Maximum area of a piece of cake
    • InvalidTransactions

      public static final java.util.Collection<java.lang.String> InvalidTransactions​(java.lang.String[] transactionArray)
      A transaction is possibly invalid if: the amount exceeds $1000, or; if it occurs within (and including) 60 minutes of another transaction with the same name in a different city. Each transaction string transactions[i] consists of comma separated values representing the name, time (in minutes), amount, and city of the transaction. Given a list of transactions, return a list of transactions that are possibly invalid. You may return the answer in any order.
      Parameters:
      transactionArray - Array of Transactions
      Returns:
      Array of Invalid Transactions
    • MaximumProductSubarray

      public static final int MaximumProductSubarray​(int[] numberArray)
      Given an integer array, find the contiguous sub-array within an array (containing at least one number) which has the largest product.
      Parameters:
      numberArray - The Number Array
      Returns:
      The Maximum Product
    • SubarrayMinimum

      public static final int SubarrayMinimum​(int[] numberArray)
      Given an array of integers, find the sum of min(B), where B ranges over every (contiguous) sub-array.
      Parameters:
      numberArray - Array if Integers
      Returns:
      Sum of min(B)
    • FourSum

      public static final java.util.Collection<java.util.List<java.lang.Integer>> FourSum​(int[] numberArray, int target)
      Given an array of n integers and an integer target, are there elements a, b, c, and d in the array such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.
      Parameters:
      numberArray - The Number Array
      target - Target
      Returns:
      Collection of Unique Quadruplets
    • MaximumSubarraySum

      public static final int MaximumSubarraySum​(int[] numberArray)
      Compute the Maximum Sum of any Sub-array
      Parameters:
      numberArray - The Number Array
      Returns:
      The Maximum Sum of any Sub-array
    • MinimumSubarraySum

      public static final int MinimumSubarraySum​(int[] numberArray)
      Compute the Minimum Sum of any Sub-array
      Parameters:
      numberArray - The Number Array
      Returns:
      The Minimum Sum of any Sub-array
    • MaximumSubarraySumCircular

      public static final double MaximumSubarraySumCircular​(int[] numberArray)
      Given a circular array C of integers represented by A, find the maximum possible sum of a non-empty sub-array 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 lte i lt A.length, and C[i+A.length] = C[i] when i gte 0.) Also, a sub-array may only include each element of the fixed buffer A at most once. (Formally, for a sub-array C[i], C[i+1], ..., C[j], there does not exist i lte k1, k2 gte j with k1 % A.length = k2 % A.length.)
      Parameters:
      numberArray - The Number Array
      Returns:
      The Maximum Sum of any Circular Sub-array
    • SpiralMatrixOrder

      public static final java.util.List<java.lang.Integer> SpiralMatrixOrder​(int[][] matrix)
      Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
      Parameters:
      matrix - m x n Matrix
      Returns:
      Elements of the matrix in spiral order.
    • UniquePathsWithObstacles

      public static final int UniquePathsWithObstacles​(int[][] obstacleGrid)
      A robot is located at the top-left corner of a m x n grid. The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid. Now consider if some obstacles are added to the grids. How many unique paths would there be?
      Parameters:
      obstacleGrid - The Obstacle Grid
      Returns:
      Count of the Unique Paths
    • CanMakePalindromeQueries

      public static final java.util.List<java.lang.Boolean> CanMakePalindromeQueries​(java.lang.String s, int[][] queries)
      Given a string s, we make queries on substrings of s. For each query queries[i] = [left, right, k], we may rearrange the substring s[left], ..., s[right], and then choose up to k of them to replace with any lower-case English letter. If the substring is possible to be a palindrome string after the operations above, the result of the query is true. Otherwise, the result is false. Return an array answer[], where answer[i] is the result of the i-th query queries[i]. Note that: Each letter is counted individually for replacement so if for example s[left..right] = "aaa", and k = 2, we can only replace two of the letters. (Also, note that the initial string s is never modified by any query.)
      Parameters:
      s - Input String
      queries - Array of Queries
      Returns:
      List of Query Results
    • ArrayPairList

      public static final java.util.List<int[]> ArrayPairList​(int[] numberArray, int x)
      Find all pairs of integers in the array which have difference equal to the number d.
      Parameters:
      numberArray - The Number Array
      x - The Difference
      Returns:
      All pairs of integers in the array which have difference equal to the number d.
    • MaximumNumberOfFamilies

      public static final int MaximumNumberOfFamilies​(int n, int[][] reservedSeats)
      A cinema has n rows of seats, numbered from 1 to n and there are ten seats in each row, labeled from 1 to 10. Given the array reservedSeats containing the numbers of seats already reserved, for example, reservedSeats[i] = [3,8] means the seat located in row 3 and labeled with 8 is already reserved. Return the maximum number of four-person groups you can assign on the cinema seats. A four-person group occupies four adjacent seats in one single row. Seats across an aisle (such as [3,3] and [3,4]) are not considered to be adjacent, but there is an exceptional case on which an aisle split a four-person group, in that case, the aisle split a four-person group in the middle, which means to have two people on each side.
      Parameters:
      n - Number of Rows
      reservedSeats - Locations of Reserved Seats
      Returns:
      Maximum number of four-person groups.
    • CanJumpToLastIndex

      public static final boolean CanJumpToLastIndex​(int[] numberArray)
      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.
      Parameters:
      numberArray - Array of non-negative Integers
      Returns:
      TRUE - The Last Index can be reached.
    • WordExistsInBoard

      public static final boolean WordExistsInBoard​(char[][] board, java.lang.String word)
      Given a 2D board and a word, find if the word exists in the grid. The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.
      Parameters:
      board - The Board
      word - The Word
      Returns:
      TRUE - The Word exists on the board
    • ReverseMatchPossible

      public static final boolean ReverseMatchPossible​(int[] a, int[] b)
      Check if Reverse match is Possible
      Parameters:
      a - Array A
      b - Array B
      Returns:
      TRUE - Reverse Match is Possible
    • FindSignatureCount

      public static final int[] FindSignatureCount​(int[] studentArray)
      There are n students, numbered from 1 to n, each with their own year-book. They would like to pass their year- books around and get them signed by other students. You are given a list of n integers arr[1..n], which is guaranteed to be a permutation of 1..n (in other words, it includes the integers from 1 to n exactly once each, in some order). The meaning of this list is described below. Initially, each student is holding their own year-book. The students will then repeat the following two steps each minute: Each student i will first sign the year-book that they're currently holding (which may either belong to themselves or to another student), and then they'll pass it to student arr[i]. It is possible that arr[i] = i for any given i, in which case student i will pass their year-book back to themselves. Once a student has received their own year-book back, they will hold on to it and no longer participate in the passing process. It is guaranteed that, for any possible valid input, each student will eventually receive their own year-book back and will never end up holding more than one year-book at a time. You must compute a list of n integers output, whose ith element is equal to the number of signatures that will be present in student i's year-book once they receive it back.
      Parameters:
      studentArray - The Starting Array
      Returns:
      The Signature Count Array
    • CountSubArrays

      public static final int[] CountSubArrays​(int[] arr)
      You are given an array a of N integers. For each index i, you are required to determine the number of contiguous sub-arrays that fulfills the following conditions: The value at index i must be the maximum element in the contiguous subarrays, and: These contiguous subarrays must either start from or end on index i.
      Parameters:
      arr - Input Array
      Returns:
      Number of Contiguous Sub-arrays
    • KClosestPoints

      public static final int[][] KClosestPoints​(int[][] pointGrid, int k)
      Extract the K-Closest Points
      Parameters:
      pointGrid - Grid of Points
      k - K
      Returns:
      K-Closest Points
    • MergeSortedArrays

      public static final int[] MergeSortedArrays​(int[][] arrayOfArrays)
      Merge the Array of Sorted Arrays into a Single Array
      Parameters:
      arrayOfArrays - Array of Sorted Arrays
      Returns:
      Resulting Single Array
    • NextGreaterElement

      public static final int[] NextGreaterElement​(int[] numberArray)
      Given a circular array (the next element of the last element is the first element of the array), print the Next Greater Number for every element. The Next Greater Number of a number x is the first greater number to its traversing-order next in the array, which means you could search circularly to find its next greater number. If it doesn't exist, output -1 for this number.
      Parameters:
      numberArray - Input Number Array
      Returns:
      Array of Next Greater Numbers
    • NearbyAlmostDuplicate

      public static final boolean NearbyAlmostDuplicate​(int[] numberArray, int k, int t)
      Given an array of integers, find out whether there are two distinct indices i and j in the array such that the absolute difference between two numbers in it is at most t and the absolute difference between i and j is at most k.
      Parameters:
      numberArray - The Number Array
      k - Index Difference Bound
      t - Value Difference Bound
      Returns:
      TRUE - There is a near-by Duplicate
    • ContinuousSubarraySum

      public static final boolean ContinuousSubarraySum​(int[] numberArray, int k)
      Given a list of non-negative numbers and a target integer k, check if the array has a continuous sub-array of size at least 2 that sums up to a multiple of k, that is, sums up to n*k where n is also an integer.
      Parameters:
      numberArray - The Number Array
      k - Target Sum k
      Returns:
      TRUE - The array has a continuous sub-array of size at least 2 that sums up to a multiple of k
    • KConcatenatedMaximumSum

      public static final int KConcatenatedMaximumSum​(int[] numberArray, int k)
      Given an integer array arr and an integer k, modify the array by repeating it k times. For example, if the array is [1, 2] and k = 3 then the modified array will be [1, 2, 1, 2, 1, 2]. Return the maximum sub-array sum in the modified array. Note that the length of the sub-array can be 0 and its sum in that case is 0.
      Parameters:
      numberArray - The Number Array
      k - The Repeat Count
      Returns:
      Maximum sub-array sum in the modified array
    • WiggleSort

      public static final boolean WiggleSort​(int[] numberArray)
      Given an unsorted array numberArray, reorder it such that numberArray[0] le numberArray[1] ge numberArray[2] le numberArray[3]....
      Parameters:
      numberArray - Number Array
      Returns:
      TRUE - The Number Array is Wiggle Sorted
    • TargetSum

      public static final int TargetSum​(int[] numberArray, int target)
      Count the Number of Ways to reach the Target
      Parameters:
      numberArray - The Input Array
      target - The Target
      Returns:
      The Number of Ways to reach the Target
    • UniqueElementsInSortedArray

      public static final int UniqueElementsInSortedArray​(int[] numberArray)
      Count the Unique Elements in the Sorted Array
      Parameters:
      numberArray - The Number Array
      Returns:
      Count of the Unique Elements in the Sorted Array
    • GeneratePathCombinations

      public static final java.util.Set<java.util.List<java.lang.Integer>> GeneratePathCombinations​(int[] numberArray, int target)
      Generate the Set of the Location Paths that meet the specified Target
      Parameters:
      numberArray - Input Array
      target - The Target
      Returns:
      The Set of the Location Paths that meet the specified Target
    • FirstAndLastPosition

      public static final int[] FirstAndLastPosition​(int[] numberArray, int target)
      Find the First and the Last Locations of the Target in the Array
      Parameters:
      numberArray - The Number Array
      target - The Target
      Returns:
      The First and the Last Locations of the Target in the Array
    • ProductOfArrayExceptSelf

      public static final int[] ProductOfArrayExceptSelf​(int[] numberArray)
      Compute the Array of Product of Array Except Self
      Parameters:
      numberArray - The Input Array
      Returns:
      The Array of Product of Array Except Self
    • IslandCounter

      public static final int IslandCounter​(int[][] grid)
      Count the Number of Islands in the Grid
      Parameters:
      grid - The Grid
      Returns:
      The Number of Islands in the Grid
    • PancakeFlipSort

      public static final int[] PancakeFlipSort​(int[] numberArray)
      Implement the Pancake Flip Sort
      Parameters:
      numberArray - The Input Array
      Returns:
      Array of Sorted Pancake Flips
    • MinimumConsumptionRate

      public static final int MinimumConsumptionRate​(int[] lotSizeArray, int totalTime)
      Calculate the Minimum Consumption Rate of the Array of Lot Sizes within the Total Time
      Parameters:
      lotSizeArray - Array of Lot Sizes
      totalTime - The Total Time
      Returns:
      The Minimum Consumption Rate
    • CollapseOverlappingRanges

      public static final java.util.Collection<int[]> CollapseOverlappingRanges​(java.util.List<int[]> rangeList)
      Collapse any Overlapping Ranges inside the Specified List
      Parameters:
      rangeList - Ranges in the List
      Returns:
      Collection of the Collapsed Ranges
    • SliceOverlappingRanges

      public static final java.util.TreeMap<java.lang.Integer,​java.lang.Integer> SliceOverlappingRanges​(java.util.List<int[]> rangeList)
      Generate a Counter Map of the Overlapping Slice Ranges
      Parameters:
      rangeList - The Range List
      Returns:
      Counter Map of the Overlapping Slice Ranges
    • MinimumOverallAwkwardness

      public static final int MinimumOverallAwkwardness​(int[] heightArray)
      There are n guests attending a dinner party, numbered from 1 to n. The ith guest has a height of heightArray[i] inches. The guests will sit down at a circular table which has n seats, numbered from 1 to n in clockwise order around the table. As the host, you will choose how to arrange the guests, one per seat. Note that there are n! possible permutations of seat assignments. Once the guests have sat down, the awkwardness between a pair of guests sitting in adjacent seats is defined as the absolute difference between their two heights. Note that, because the table is circular, seats 1 and n are considered to be adjacent to one another, and that there are therefore n pairs of adjacent guests. The overall awkwardness of the seating arrangement is then defined as the maximum awkwardness of any pair of adjacent guests. Determine the minimum possible overall awkwardness of any seating arrangement.
      Parameters:
      heightArray - The Height Array
      Returns:
      The Maximum Awkwardness of the Arrangement
    • TargetApproachPathList

      public static final java.util.List<java.lang.String> TargetApproachPathList​(int[] numberArray, int target)
      Given a list of integers and a target. There are 2 symbols + and -. For each integer, choose one from + and - as its new symbol. Find out the ways to assign symbols to make sum of integers equal to target.
      Parameters:
      numberArray - The Number Array
      target - The Sum Target
      Returns:
      List of the Target Approach Paths
    • BODMAS

      public static final int BODMAS​(java.lang.String s) throws java.lang.Exception
      Execute a BODMAS Evaluation of the Expression
      Parameters:
      s - The Expression String
      Returns:
      result of the BODMAS Evaluation
      Throws:
      java.lang.Exception - Thrown if the Inputs are Invalid
    • ExpressionOperatorPathList

      public static final java.util.List<java.lang.String> ExpressionOperatorPathList​(int[] numberArray, int target)
      Given a string that contains only digits 0-9 and a target value, return all possibilities to add binary operators (not unary) +, -, or * between the digits so they evaluate to the target value.
      Parameters:
      numberArray - The Number Array
      target - The Target
      Returns:
      List of the Expression Possibilities
    • InsertIntoNonOverlappingIntervals

      public static final java.util.List<int[]> InsertIntoNonOverlappingIntervals​(int[][] intervals, int[] newInterval)
      Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary). Assume that the intervals were initially sorted according to their start times.
      Parameters:
      intervals - Array of the Sorted Intervals
      newInterval - The New Interval
      Returns:
      List of the Merged Intervals
    • SortColor

      public static final void SortColor​(int[] numberArray)
      Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue. Here, use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. Note: You are not suppose to use the library's sort function for this problem.
      Parameters:
      numberArray - The Number Array
    • SparseMatrixRepresentation

      public static final java.util.Map<java.lang.String,​java.lang.Integer> SparseMatrixRepresentation​(int[][] matrix)
      Construct a Sparse Matrix Representation
      Parameters:
      matrix - The Sparse Matrix
      Returns:
      Th Sparse Matrix Representation
    • SparseMatrixDotProduct

      public static final int SparseMatrixDotProduct​(int[][] matrix)
      Compute the Dot Product of the Sparse Matrix
      Parameters:
      matrix - The Sparse Matrix
      Returns:
      Dot Product of the Sparse Matrix
    • LocationInSortedArray

      public static final int[] LocationInSortedArray​(int[] numberArray, int target)
      Given an array of integers sorted in ascending order, find the starting and ending position of a given target value. The algorithm's runtime complexity must be in the order of O(log n). If the target is not found in the array, return [-1, -1].
      Parameters:
      numberArray - The Sorted Number Array
      target - The Target Number
      Returns:
      The starting and ending positions.
    • RandomMinesInGrid

      public static final int[][] RandomMinesInGrid​(int m, int n, int k)
      Given a m-by-n grid, generate k mines on this grid randomly. Each cell should have equal probability of k / (m * n) of being chosen.
      Parameters:
      m - m
      n - n
      k - k
      Returns:
      k Random Mines on this Grid
    • EnumerateDiagonalFlipFlop

      public static final int[] EnumerateDiagonalFlipFlop​(int[][] matrix)
      Given a matrix, return all elements of the matrix in diagonal flip-flop order.
      Parameters:
      matrix - The Matrix
      Returns:
      Elements of the matrix in diagonal flip-flop order
    • EnumerateDiagonalOrder

      public static final java.util.List<java.util.List<java.lang.Integer>> EnumerateDiagonalOrder​(int[][] matrix)
      Given a matrix, return all elements of the matrix in anti-diagonal order.
      Parameters:
      matrix - The Matrix
      Returns:
      Elements of the matrix in anti-diagonal order.
    • SlidingWindowMaximum

      public static final int[] SlidingWindowMaximum​(int[] numberArray, int k)
      Build the Array of Maximum Sliding Window of Size k
      Parameters:
      numberArray - The Number Array
      k - Size
      Returns:
      The Array of Maximum Sliding Window of Size k
    • SetMatrixZeroes

      public static final boolean SetMatrixZeroes​(int[][] matrix)
      Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in-place.
      Parameters:
      matrix - The Given Matrix
      Returns:
      TRUE - The Altered Matrix
    • IncreasingTripletSubsequenceExists

      public static final boolean IncreasingTripletSubsequenceExists​(int[] numberArray)
      Given an unsorted array return whether an increasing subsequence of length 3 exists or not in the array. Formally the function should: Return true if there exists i, j, k such that arr[i] lt arr[j] lt arr[k] given 0 le i lt j lt le ≤ n-1 else return false. Note: Your algorithm should run in O(n) time complexity and O(1) space complexity.
      Parameters:
      numberArray - The Number Array
      Returns:
      TRUE - Increasing Triplet Subsequence Exists
    • FourSumCount

      public static final int FourSumCount​(int[] numberArrayA, int[] numberArrayB, int[] numberArrayC, int[] numberArrayD)
      Given four lists A, B, C, D of integer values, compute how many tuples (i, j, k, l) there are such that A[i] + B[j] + C[k] + D[l] is zero.
      Parameters:
      numberArrayA - Number Array A
      numberArrayB - Number Array B
      numberArrayC - Number Array C
      numberArrayD - Number Array D
      Returns:
      Count of the Zero 4 Sums
    • MaximumAreaUnderContainer

      public static final int[] MaximumAreaUnderContainer​(int[] heightArray)
      Given non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two end-points of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.
      Parameters:
      heightArray - Array of Heights
      Returns:
      The Line Locations and the Maximum Container Area
    • FirstMisingPositiveInteger

      public static final int FirstMisingPositiveInteger​(int[] numberArray)
      Given an unsorted integer array, find the smallest missing positive integer.
      Parameters:
      numberArray - Unsorted Number Array
      Returns:
      Smallest Missing Positive Integer
    • IdentifyDuplicate

      public static final int IdentifyDuplicate​(int[] numberArray)
      Given an array containing n + 1 integers where each integer is between 1 and n (inclusive), assuming there is only one duplicate number, find the duplicate one.
      Parameters:
      numberArray - The Number Array
      Returns:
      The Duplicate Number
    • RainWaterCatchmentArea

      public static final int RainWaterCatchmentArea​(int[] segmentHeightArray)
      Implement the Rain-water Catchment Area given the array of Heights
      Parameters:
      segmentHeightArray - Array of Heights
      Returns:
      The Rain-water Catchment Area
    • QueueReconstructionByHeight

      public static final int[] QueueReconstructionByHeight​(int[][] heightOrderArray)
      A Random list of people standing in a queue. Each person is described by a pair of integers (h, k), where h is the height of the person and k is the number of people in front of this person who have a height greater than or equal to h. Reconstruct the queue.
      Parameters:
      heightOrderArray - The Height+Order Tuple Array
      Returns:
      The Queue Array
    • MedianOfSortedArrays

      public static final double MedianOfSortedArrays​(int[] sortedArray1, int[] sortedArray2)
      There are two sorted arrays of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). Assume arrays cannot be both empty.
      Parameters:
      sortedArray1 - Sorted Array #1
      sortedArray2 - Sorted Array #2
      Returns:
      The Overall Median
    • SortedMatrixKthElement

      public static final int SortedMatrixKthElement​(int[][] matrix, int k)
      Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in the matrix. Note that it is the kth smallest element in the sorted order, not the kth distinct element.
      Parameters:
      matrix - The Matrix
      k - kth Element
      Returns:
      kth Smallest Element
    • LargestRectangleInHistogram

      public static final int LargestRectangleInHistogram​(int[] heightArray)
      Given non-negative integers representing the histogram bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.
      Parameters:
      heightArray - The Bar Array
      Returns:
      Area of the Largest Rectangle
    • GenerateSkyline

      public static final java.util.TreeMap<java.lang.Integer,​int[]> GenerateSkyline​(java.util.TreeMap<java.lang.Integer,​int[]> skscraperMap)
      A city skyline is the outer contour of the silhouette formed by all the buildings in that city when viewed from a distance. Given the locations and height of all the buildings as shown on a cityscape photo, output the skyline formed by these buildings collectively.
      Parameters:
      skscraperMap - Cityscape represented as a Map of Skyscapers
      Returns:
      The Skyline Map
    • StrategicBalloonBurstSum

      public static final int StrategicBalloonBurstSum​(int[] balloonCoinArray)
      Given an array of balloons, each balloon is painted with a number on it represented by array. You are asked to burst all the balloons. If the you burst balloon i you will get nums[left] * nums[i] * nums[right] coins. Here left and right are adjacent indices of i. After the burst, the left and right then becomes adjacent. Find the maximum coins you can collect by bursting the balloons wisely.
      Parameters:
      balloonCoinArray - Balloon Coin Array
      Returns:
      Wise Balloon Burst Sum
    • Median

      public static final double Median​(int[] numberArray)
      Evaluate the Array Median
      Parameters:
      numberArray - The Number Array
      Returns:
      The Array Median
    • WiggleSort2

      public static final boolean WiggleSort2​(int[] numberArray)
      Implement the Wiggle Sort Version 2
      Parameters:
      numberArray - The Number Array
      Returns:
      TRUE - The Sort Implementation done
    • BaseballScore

      public static final int BaseballScore​(java.lang.String[] scoreEventArray)
      Tom plays a game in which he throws a baseball at various blocks marked with a symbol. Each block comes with a symbol which can be an integer, ‘X’, ‘+’, or ‘Z’. Given a list of strings represent blocks, return the final score.
      Parameters:
      scoreEventArray - Array of the Score/Event Strings
      Returns:
      The Baseball Score
    • InventoryProfit

      public static final int InventoryProfit​(int[] inventoryArray, int orderCount)
      A company has several suppliers for its products. For each of the products, the stock is represented by a list of a number of items for each supplier. As items are purchased, the supplier raises the price by 1 per item purchased. Let's assume Amazon's profit on any single item is the same as the number of items the supplier has left. For example, if a supplier has 4 items, company's profit on the first item sold is 4, then 3, then 2 and the profit of the last one is 1. Given a list where each value in the list is the number of the item at a given supplier and also given the number of items to be ordered, write an algorithm to find the highest profit that can be generated for the given product.
      Parameters:
      inventoryArray - The Number of Suppliers
      orderCount - The Order Count
      Returns:
      The Inventory Profit
    • MaximumAvailableDiskSpace

      public static final int MaximumAvailableDiskSpace​(int[] diskSpaceArray, int segmentLength)
      Company A is performing an analysis on the computers at one of its offices. The computers are spaced along a single row. The analysis is performed in the following way: Choose a contiguous segment of a certain number of computers, starting from the beginning of the row. Analyze the available hard disk space on each of the computers. Determine the minimum available disk space within this segment. After performing these steps for the first segment, it is then repeated for the next segment, continuing this procedure until the end of the row (i.e. if the segment size is 4, computers 1 to 4 would be analyzed, then 2 to 5, etc.) Given this analysis procedure, write an algorithm to find the maximum available disk space among all the minima that are found during the analysis.
      Parameters:
      diskSpaceArray - Array of Disk Space
      segmentLength - The Segment Length
      Returns:
      The Maximum Available Disk Space
    • PopulationInfection

      public static final int PopulationInfection​(int[][] infectionMatrix)
      Given a 2D grid, each cell is either a zombie or a human. Zombies can turn adjacent (up/down/left/right) human beings into zombies every day. Find out how many days does it take to infect all humans?
      Parameters:
      infectionMatrix - The Infection Matrix
      Returns:
      Number of Days to infect the entire Population
    • BalancedPartition

      public static final boolean BalancedPartition​(int[] numberArray)
      Given an array containing only positive integers, return if you can pick two integers from the array which cuts the array into three pieces such that the sum of elements in all pieces is equal.
      Parameters:
      numberArray - The Number Array
      Returns:
      TRUE - A Balanced Partition Exists
    • OptimizeMemoryUsage

      public static final java.util.List<int[]> OptimizeMemoryUsage​(int[] foregroundTasks, int[] backgroundTasks, int k)
      Give a computer with total k memory space, and an array of foreground tasks and background tasks the computer needs to do. Write an algorithm to find a pair of tasks from each array to maximize the memory usage. Notice the tasks could be done without origin order.
      Parameters:
      foregroundTasks - Array of Foreground Tasks
      backgroundTasks - Array of Background Tasks
      k - Memory Limit
      Returns:
      List of [fore, back] pairs
    • MaxPathScore

      public static final int MaxPathScore​(int[][] matrix)
      Given a two 2D matrix, find the max score of a path from the upper left cell to bottom right cell that doesn't visit any of the cells twice. The score of a path is the minimum value in that path.
      Parameters:
      matrix - Matrix of Node Values
      Returns:
      The Maximum Path Score
    • DiscountedSale

      public static final int DiscountedSale​(int[] priceArray, java.util.List<java.lang.Integer> nonDiscountedItems)
      A shopkeeper has a sale to complete and has arranged the items being sold in a list. Starting from the left, the shop keeper rings up each item at its full price less the price of the first lower or equally priced item to its right. If there is no item to the right that costs less than or equal to the current item's price the current item is sold at full price. Print total cost of all items. Also print the list of integers representing the indexes of the non- discounted items in ascending index order.
      Parameters:
      priceArray - Array of Item Prices
      nonDiscountedItems - List of Non-discounted Items
      Returns:
      Total Cost of Discounted Items
    • ShortestSubarrayAtLeastSum

      public static final int ShortestSubarrayAtLeastSum​(int[] numberArray, int sum)
      Given an integer array and an integer, return the length of the shortest non-empty subarray with a sum of at least sum. If there is no such subarray, return -1. A subarray is a contiguous part of an array.
      Parameters:
      numberArray - Array of Numbers
      sum - The Target Sum
      Returns:
      Size of the Shortest Subarray
    • CountWaysToSeparate

      public static final int CountWaysToSeparate​(java.lang.String numberStr)
      Count the Number of Ways to Separate the Number
      Parameters:
      numberStr - The Number
      Returns:
      Number of Ways to Separate the Number
    • SplitIntoSameAverage

      public static final boolean SplitIntoSameAverage​(double[] numberArray)
      Check if the Array can be split so that the Two Sides add to the same
      Parameters:
      numberArray - The Input Array
      Returns:
      TRUE - The Array can be split so that the Two Sides add to the same
    • MaximumPointsInLine

      public static final int MaximumPointsInLine​(int[][] points)
      Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane, return the maximum number of points that lie on the same straight line.
      Parameters:
      points - Points Grid
      Returns:
      Maximum Points In Line
    • ConversionToNondecreasing

      public static final boolean ConversionToNondecreasing​(int[] numberArray)
      Given an array of integers, your task is to check if it could become non-decreasing by modifying at most one element. We define an array is non-decreasing if nums[i] le nums[i + 1] holds for every i (0-based) such that (0 le i le n - 2).
      Parameters:
      numberArray - Number Array
      Returns:
      TRUE - The Conversion is Possible
    • PartitionArrayMinimizeSum

      public static final int PartitionArrayMinimizeSum​(int[] numberArray)
      You are given an integer array of 2 * n integers. You need to partition it into two arrays of length n to minimize the absolute difference of the sums of the arrays. To partition the array, put each element into one of the two arrays. Return the minimum possible absolute difference.
      Parameters:
      numberArray - The Number Array
      Returns:
      Minimum Possible Difference
    • JumpGameDestinationReachable

      public static final boolean JumpGameDestinationReachable​(java.lang.String s, int minJump, int maxJump)
      Indicate the Destination is Reachable
      Parameters:
      s - The String
      minJump - Lower Jump Bound
      maxJump - Upper Jump Bound
      Returns:
      TRUE - The Destination is Reachable
    • KConcatenationMaximumSum

      public static final int KConcatenationMaximumSum​(int[] numberArray, int k)
      Given an integer array numberArray and an integer k, modify the array by repeating it k times. For example, if arr = [1, 2] and k = 3 then the modified array will be [1, 2, 1, 2, 1, 2]. Return the maximum sub-array sum in the modified array. Note that the length of the sub-array can be 0 and its sum in that case is 0. As the answer can be very large, return the answer modulo 109 + 7.
      Parameters:
      numberArray - Number Array
      k - K
      Returns:
      Maximum Sum after k Concatenations
    • ReachTargetMinimumJumps

      public static final int ReachTargetMinimumJumps​(int[] forbiddenLocationArray, int a, int b, int target)
      A certain bug's home is on the x-axis at position x. Help them get there from position 0. The bug jumps according to the following rules: It can jump exactly a positions forward (to the right). It can jump exactly b positions backward (to the left). It cannot jump backward twice in a row. It cannot jump to any forbidden positions. The bug may jump forward beyond its home, but it cannot jump to positions numbered with negative integers. Given an array of integers forbidden, where forbidden[i] means that the bug cannot jump to the position forbidden[i], and integers a, b, and x, return the minimum number of jumps needed for the bug to reach its home. If there is no possible sequence of jumps that lands the bug on position x, return -1.
      Parameters:
      forbiddenLocationArray - Array of Forbidden Locations
      a - Steps of Right Jump
      b - Steps of Left Jump
      target - Target
      Returns:
      Minimum Steps to reach Target
    • ClosestNextPrimeNumber

      public static final int ClosestNextPrimeNumber​(int number)
      Given an integer n, return the smallest prime palindrome greater than or equal to n. An integer is prime if it has exactly two divisors: 1 and itself. Note that 1 is not a prime number. For example, 2, 3, 5, 7, 11, and 13 are all primes. An integer is a palindrome if it reads the same from left to right as it does from right to left. For example, 101 and 12321 are palindromes. The test cases are generated so that the answer always exists and is in the range [2, 2 * 108].
      Parameters:
      number - Given Number
      Returns:
      Closest Next Prime Palindrome
    • ContinuousSubarraySumMod

      public static final boolean ContinuousSubarraySumMod​(int[] numberArray, int k)
      Given an integer array and an integer k, return true if the array has a continuous sub-array of size at least two whose elements sum up to a multiple of k, or false otherwise. An integer x is a multiple of k if there exists an integer n such that x = n * k. 0 is always a multiple of k.
      Parameters:
      numberArray - Number Array
      k - K
      Returns:
      TRUE - The array has a continuous sub-array of size at least two whose elements sum up to a multiple of k
    • main

      public static final void main​(java.lang.String[] argumentArray) throws java.lang.Exception
      Entry Point
      Parameters:
      argumentArray - Argument Array
      Throws:
      java.lang.Exception - Thrown if Exception Encountered