Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
205 changes: 205 additions & 0 deletions README.md

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin)
[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork)

## 1801\. Number of Orders in the Backlog

Medium

You are given a 2D integer array `orders`, where each <code>orders[i] = [price<sub>i</sub>, amount<sub>i</sub>, orderType<sub>i</sub>]</code> denotes that <code>amount<sub>i</sub></code> orders have been placed of type <code>orderType<sub>i</sub></code> at the price <code>price<sub>i</sub></code>. The <code>orderType<sub>i</sub></code> is:

* `0` if it is a batch of `buy` orders, or
* `1` if it is a batch of `sell` orders.

Note that `orders[i]` represents a batch of <code>amount<sub>i</sub></code> independent orders with the same price and order type. All orders represented by `orders[i]` will be placed before all orders represented by `orders[i+1]` for all valid `i`.

There is a **backlog** that consists of orders that have not been executed. The backlog is initially empty. When an order is placed, the following happens:

* If the order is a `buy` order, you look at the `sell` order with the **smallest** price in the backlog. If that `sell` order's price is **smaller than or equal to** the current `buy` order's price, they will match and be executed, and that `sell` order will be removed from the backlog. Else, the `buy` order is added to the backlog.
* Vice versa, if the order is a `sell` order, you look at the `buy` order with the **largest** price in the backlog. If that `buy` order's price is **larger than or equal to** the current `sell` order's price, they will match and be executed, and that `buy` order will be removed from the backlog. Else, the `sell` order is added to the backlog.

Return _the total **amount** of orders in the backlog after placing all the orders from the input_. Since this number can be large, return it **modulo** <code>10<sup>9</sup> + 7</code>.

**Example 1:**

![](https://assets.leetcode.com/uploads/2021/03/11/ex1.png)

**Input:** orders = \[\[10,5,0],[15,2,1],[25,1,1],[30,4,0]]

**Output:** 6

**Explanation:** Here is what happens with the orders:

- 5 orders of type buy with price 10 are placed. There are no sell orders, so the 5 orders are added to the backlog.

- 2 orders of type sell with price 15 are placed. There are no buy orders with prices larger than or equal to 15, so the 2 orders are added to the backlog.

- 1 order of type sell with price 25 is placed. There are no buy orders with prices larger than or equal to 25 in the backlog, so this order is added to the backlog.

- 4 orders of type buy with price 30 are placed. The first 2 orders are matched with the 2 sell orders of the least price, which is 15 and these 2 sell orders are removed from the backlog. The 3<sup>rd</sup> order is matched with the sell order of the least price, which is 25 and this sell order is removed from the backlog. Then, there are no more sell orders in the backlog, so the 4<sup>th</sup> order is added to the backlog. Finally, the backlog has 5 buy orders with price 10, and 1 buy order with price 30. So the total number of orders in the backlog is 6.

**Example 2:**

![](https://assets.leetcode.com/uploads/2021/03/11/ex2.png)

**Input:** orders = \[\[7,1000000000,1],[15,3,0],[5,999999995,0],[5,1,1]]

**Output:** 999999984

**Explanation:** Here is what happens with the orders:

- 10<sup>9</sup> orders of type sell with price 7 are placed. There are no buy orders, so the 10<sup>9</sup> orders are added to the backlog.

- 3 orders of type buy with price 15 are placed. They are matched with the 3 sell orders with the least price which is 7, and those 3 sell orders are removed from the backlog. - 999999995 orders of type buy with price 5 are placed. The least price of a sell order is 7, so the 999999995 orders are added to the backlog.

- 1 order of type sell with price 5 is placed. It is matched with the buy order of the highest price, which is 5, and that buy order is removed from the backlog. Finally, the backlog has (1000000000-3) sell orders with price 7, and (999999995-1) buy orders with price 5. So the total number of orders = 1999999991, which is equal to 999999984 % (10<sup>9</sup> + 7).

**Constraints:**

* <code>1 <= orders.length <= 10<sup>5</sup></code>
* `orders[i].length == 3`
* <code>1 <= price<sub>i</sub>, amount<sub>i</sub> <= 10<sup>9</sup></code>
* <code>orderType<sub>i</sub></code> is either `0` or `1`.

## Solution

```kotlin
import java.util.PriorityQueue

class Solution {
private class Order(var price: Int, var qty: Int)

fun getNumberOfBacklogOrders(orders: Array<IntArray>): Int {
val sell = PriorityQueue(
compareBy { a: Order -> a.price }
)
val buy = PriorityQueue { a: Order, b: Order -> b.price - a.price }
for (order in orders) {
val price = order[0]
var amount = order[1]
val type = order[2]
if (type == 0) {
while (sell.isNotEmpty() && sell.peek().price <= price && amount > 0) {
val ord = sell.peek()
val toRemove = amount.coerceAtMost(ord.qty)
ord.qty -= toRemove
amount -= toRemove
if (ord.qty == 0) {
sell.poll()
}
}
if (amount > 0) {
buy.add(Order(price, amount))
}
} else {
while (buy.isNotEmpty() && buy.peek().price >= price && amount > 0) {
val ord = buy.peek()
val toRemove = amount.coerceAtMost(ord.qty)
ord.qty -= toRemove
amount -= toRemove
if (ord.qty == 0) {
buy.poll()
}
}
if (amount > 0) {
sell.add(Order(price, amount))
}
}
}
var sellCount: Long = 0
for (ord in sell) {
sellCount += ord.qty.toLong()
}
var buyCount: Long = 0
for (ord in buy) {
buyCount += ord.qty.toLong()
}
val total = sellCount + buyCount
return (total % 1000000007L).toInt()
}
}
```
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin)
[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork)

## 1802\. Maximum Value at a Given Index in a Bounded Array

Medium

You are given three positive integers: `n`, `index`, and `maxSum`. You want to construct an array `nums` (**0-indexed**) that satisfies the following conditions:

* `nums.length == n`
* `nums[i]` is a **positive** integer where `0 <= i < n`.
* `abs(nums[i] - nums[i+1]) <= 1` where `0 <= i < n-1`.
* The sum of all the elements of `nums` does not exceed `maxSum`.
* `nums[index]` is **maximized**.

Return `nums[index]` _of the constructed array_.

Note that `abs(x)` equals `x` if `x >= 0`, and `-x` otherwise.

**Example 1:**

**Input:** n = 4, index = 2, maxSum = 6

**Output:** 2

**Explanation:** nums = [1,2,**2**,1] is one array that satisfies all the conditions. There are no arrays that satisfy all the conditions and have nums[2] == 3, so 2 is the maximum nums[2].

**Example 2:**

**Input:** n = 6, index = 1, maxSum = 10

**Output:** 3

**Constraints:**

* <code>1 <= n <= maxSum <= 10<sup>9</sup></code>
* `0 <= index < n`

## Solution

```kotlin
class Solution {
private fun isPossible(n: Int, index: Int, maxSum: Int, value: Int): Boolean {
val leftValue = (value - index).coerceAtLeast(0)
val rightValue = (value - (n - 1 - index)).coerceAtLeast(0)
val sumBefore = (value + leftValue).toLong() * (value - leftValue + 1) / 2
val sumAfter = (value + rightValue).toLong() * (value - rightValue + 1) / 2
return sumBefore + sumAfter - value <= maxSum
}

fun maxValue(n: Int, index: Int, maxSum: Int): Int {
var left = 0
var right = maxSum - n
while (left < right) {
val middle = (left + right + 1) / 2
if (isPossible(n, index, maxSum - n, middle)) {
left = middle
} else {
right = middle - 1
}
}
return left + 1
}
}
```
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin)
[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork)

## 1803\. Count Pairs With XOR in a Range

Hard

Given a **(0-indexed)** integer array `nums` and two integers `low` and `high`, return _the number of **nice pairs**_.

A **nice pair** is a pair `(i, j)` where `0 <= i < j < nums.length` and `low <= (nums[i] XOR nums[j]) <= high`.

**Example 1:**

**Input:** nums = [1,4,2,7], low = 2, high = 6

**Output:** 6

**Explanation:** All nice pairs (i, j) are as follows:

- (0, 1): nums[0] XOR nums[1] = 5

- (0, 2): nums[0] XOR nums[2] = 3

- (0, 3): nums[0] XOR nums[3] = 6

- (1, 2): nums[1] XOR nums[2] = 6

- (1, 3): nums[1] XOR nums[3] = 3

- (2, 3): nums[2] XOR nums[3] = 5

**Example 2:**

**Input:** nums = [9,8,4,2,1], low = 5, high = 14

**Output:** 8

**Explanation:** All nice pairs (i, j) are as follows:

- (0, 2): nums[0] XOR nums[2] = 13

- (0, 3): nums[0] XOR nums[3] = 11

- (0, 4): nums[0] XOR nums[4] = 8

- (1, 2): nums[1] XOR nums[2] = 12

- (1, 3): nums[1] XOR nums[3] = 10

- (1, 4): nums[1] XOR nums[4] = 9

- (2, 3): nums[2] XOR nums[3] = 6

- (2, 4): nums[2] XOR nums[4] = 5

**Constraints:**

* <code>1 <= nums.length <= 2 * 10<sup>4</sup></code>
* <code>1 <= nums[i] <= 2 * 10<sup>4</sup></code>
* <code>1 <= low <= high <= 2 * 10<sup>4</sup></code>

## Solution

```kotlin
class Solution {
fun countPairs(nums: IntArray, low: Int, high: Int): Int {
val root = Trie()
var pairsCount = 0
for (num in nums) {
val pairsCountHigh = countPairsWhoseXorLessThanX(num, root, high + 1)
val pairsCountLow = countPairsWhoseXorLessThanX(num, root, low)
pairsCount += pairsCountHigh - pairsCountLow
root.insertNumber(num)
}
return pairsCount
}

private fun countPairsWhoseXorLessThanX(num: Int, root: Trie, x: Int): Int {
var pairs = 0
var curr: Trie? = root
var i = 14
while (i >= 0 && curr != null) {
val numIthBit = num shr i and 1
val xIthBit = x shr i and 1
if (xIthBit == 1) {
if (curr.child[numIthBit] != null) {
pairs += curr.child[numIthBit]!!.count
}
curr = curr.child[1 - numIthBit]
} else {
curr = curr.child[numIthBit]
}
i--
}
return pairs
}

private class Trie {
var child: Array<Trie?> = arrayOfNulls(2)
var count: Int = 0

fun insertNumber(num: Int) {
var curr = this
for (i in 14 downTo 0) {
val ithBit = num shr i and 1
if (curr.child[ithBit] == null) {
curr.child[ithBit] = Trie()
}
curr.child[ithBit]!!.count++
curr = curr.child[ithBit]!!
}
}
}
}
```
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin)
[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork)

## 1805\. Number of Different Integers in a String

Easy

You are given a string `word` that consists of digits and lowercase English letters.

You will replace every non-digit character with a space. For example, `"a123bc34d8ef34"` will become `" 123 34 8 34"`. Notice that you are left with some integers that are separated by at least one space: `"123"`, `"34"`, `"8"`, and `"34"`.

Return _the number of **different** integers after performing the replacement operations on_ `word`.

Two integers are considered different if their decimal representations **without any leading zeros** are different.

**Example 1:**

**Input:** word = "a123bc34d8ef34"

**Output:** 3

**Explanation:** The three different integers are "123", "34", and "8". Notice that "34" is only counted once.

**Example 2:**

**Input:** word = "leet1234code234"

**Output:** 2

**Example 3:**

**Input:** word = "a1b01c001"

**Output:** 1

**Explanation:** The three integers "1", "01", and "001" all represent the same integer because the leading zeros are ignored when comparing their decimal values.

**Constraints:**

* `1 <= word.length <= 1000`
* `word` consists of digits and lowercase English letters.

## Solution

```kotlin
@Suppress("NAME_SHADOWING")
class Solution {
fun numDifferentIntegers(word: String): Int {
val ints: MutableSet<String> = HashSet()
val chars = word.toCharArray()
var start = -1
var stop = 0
for (i in chars.indices) {
if (chars[i] in '0'..'9') {
if (start == -1) {
start = i
}
stop = i
} else if (start != -1) {
ints.add(extractInt(chars, start, stop))
start = -1
}
}
if (start != -1) {
ints.add(extractInt(chars, start, stop))
}
return ints.size
}

private fun extractInt(chrs: CharArray, start: Int, stop: Int): String {
var start = start
val stb = StringBuilder()
while (start <= stop && chrs[start] == '0') {
start++
}
if (start >= stop) {
stb.append(chrs[stop])
} else {
while (start <= stop) {
stb.append(chrs[start++])
}
}
return stb.toString()
}
}
```
Loading