LeetCode Solutions - Page 3
1672. Richest Customer Wealth
JuniorDescription: Solve the LeetCode challenge "richest-customer-wealth" using PHP.
Code:
class Solution {
/**
* @param Integer[][] $accounts
* @return Integer
*/
function maximumWealth($accounts) {
$rs = 0;
for ($i = 0; $i < count($accounts); $i++) {
$sum = 0;
for ($j = 0; $j < count($accounts[$i]); $j++) {
$sum += $accounts[$i][$j];
}
if ($sum > $rs) {
$rs = $sum;
}
}
return $rs;
}
}
1704. Determine if String Halves Are Alike
JuniorDescription: Solve the LeetCode challenge "determine-if-string-halves-are-alike" using PHP.
Code:
class Solution {
/**
* @param String $s
* @return Boolean
*/
function halvesAreAlike($s) {
$n = strlen($s) / 2;
$vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'];
$cnt = 0;
for ($i = 0; $i < $n; $i++) {
if (in_array($s[$i], $vowels)) {
$cnt++;
}
if (in_array($s[$i + $n], $vowels)) {
$cnt--;
}
}
return $cnt == 0;
}
}
1732. Find the Highest Altitude
JuniorDescription: Solve the LeetCode challenge "find-the-highest-altitude" using PHP.
Code:
class Solution {
/**
* @param Integer[] $gain
* @return Integer
*/
function largestAltitude($gain) {
$max = 0;
for ($i = 0; $i < count($gain); $i++) {
$tmp += $gain[$i];
if ($tmp > $max) {
$max = $tmp;
}
}
return $max;
}
}
1748. Sum of Unique Elements
JuniorDescription: Solve the LeetCode challenge "sum-of-unique-elements" using PHP.
Code:
class Solution {
/**
* @param Integer[] $nums
* @return Integer
*/
function sumOfUnique($nums) {
$sum = 0;
for ($i = 0; $i < count($nums); $i++) {
$hashtable[$nums[$i]] += 1;
if ($hashtable[$nums[$i]] == 1) {
$sum += $nums[$i];
}
if ($hashtable[$nums[$i]] == 2) {
$sum -= $nums[$i];
}
}
return $sum;
}
}
1876. Substrings of Size Three with Distinct Characters
JuniorDescription: Solve the LeetCode challenge "substrings-of-size-three-with-distinct-characters" using PHP.
Code:
class Solution {
/**
* @param String $s
* @return Integer
*/
function countGoodSubstrings($s) {
$ans = 0;
$n = strlen($s);
$l = 0;
$r = 0;
$mask = 0;
while ($r < $n) {
$x = ord($s[$r]) - ord('a');
while (($mask >> $x) & 1) {
$y = ord($s[$l++]) - ord('a');
$mask ^= 1 << $y;
}
$mask |= 1 << $x;
if ($r - $l + 1 >= 3) {
$ans++;
}
$r++;
}
return $ans;
}
}
1941. Check if All Characters Have Equal Number of Occurrences
JuniorDescription: Solve the LeetCode challenge "check-if-all-characters-have-equal-number-of-occurrences" using PHP.
Code:
class Solution {
/**
* @param String $s
* @return Boolean
*/
function areOccurrencesEqual($s) {
$cnt = array_fill(0, 26, 0);
for ($i = 0; $i < strlen($s); $i++) {
$cnt[ord($s[$i]) - ord('a')]++;
}
$v = 0;
foreach ($cnt as $x) {
if ($x == 0) {
continue;
}
if ($v && $v != $x) {
return false;
}
$v = $x;
}
return true;
}
}
1945. Sum of Digits of String After Convert
JuniorDescription: Solve the LeetCode challenge "sum-of-digits-of-string-after-convert" using PHP.
Code:
class Solution {
/**
* @param String $s
* @param Integer $k
* @return Integer
*/
function getLucky($s, $k) {
$rs = '';
for ($i = 0; $i < strlen($s); $i++) {
$num = ord($s[$i]) - 96;
$rs = $rs . strval($num);
}
while ($k != 0) {
$sum = 0;
for ($j = 0; $j < strlen($rs); $j++) {
$sum += intval($rs[$j]);
}
$rs = strval($sum);
$k--;
}
return intval($rs);
}
}
1957. Delete Characters to Make Fancy String
JuniorDescription: Solve the LeetCode challenge "delete-characters-to-make-fancy-string" using PHP.
Code:
class Solution {
/**
* @param String $s
* @return String
*/
function makeFancyString($s) {
$ans = '';
for ($i = 0; $i < strlen($s); $i++) {
$c = $s[$i];
if ($i < 2 || $c !== $s[$i - 1] || $c !== $s[$i - 2]) {
$ans .= $c;
}
}
return $ans;
}
}
1984. Minimum Difference Between Highest and Lowest of K Scores
JuniorDescription: Solve the LeetCode challenge "minimum-difference-between-highest-and-lowest-of-k-scores" using PHP.
Code:
class Solution {
/**
* @param Integer[] $nums
* @param Integer $k
* @return Integer
*/
function minimumDifference($nums, $k) {
sort($nums);
$ans = 10 ** 5;
for ($i = 0; $i < count($nums) - $k + 1; $i++) {
$ans = min($ans, $nums[$i + $k - 1] - $nums[$i]);
}
return $ans;
}
}
2000. Reverse Prefix of Word
JuniorDescription: Solve the LeetCode challenge "reverse-prefix-of-word" using PHP.
Code:
class Solution {
/**
* @param String $word
* @param String $ch
* @return String
*/
function reversePrefix($word, $ch) {
$len = strlen($word);
$rs = '';
for ($i = 0; $i < $len; $i++) {
$rs = $rs . $word[$i];
if ($word[$i] == $ch) {
break;
}
}
if (strlen($rs) == $len && $rs[$len - 1] != $ch) {
return $word;
}
$rs = strrev($rs);
$rs = $rs . substr($word, strlen($rs));
return $rs;
}
}
2068. Check Whether Two Strings are Almost Equivalent
JuniorDescription: Solve the LeetCode challenge "check-whether-two-strings-are-almost-equivalent" using PHP.
Code:
class Solution {
/**
* @param String $word1
* @param String $word2
* @return Boolean
*/
function checkAlmostEquivalent($word1, $word2) {
for ($i = 0; $i < strlen($word1); $i++) {
$hashtable[$word1[$i]] += 1;
$hashtable[$word2[$i]] -= 1;
}
$keys = array_keys($hashtable);
for ($j = 0; $j < count($keys); $j++) {
if (abs($hashtable[$keys[$j]]) > 3) {
return false;
}
}
return true;
}
}
2190. Most Frequent Number Following Key In an Array
JuniorDescription: Solve the LeetCode challenge "most-frequent-number-following-key-in-an-array" using PHP.
Code:
class Solution {
function mostFrequent($nums, $key) {
$cnt = array_fill(0, max($nums) + 1, 0);
$ans = 0;
$mx = 0;
for ($i = 0; $i < count($nums) - 1; ++$i) {
if ($nums[$i] === $key) {
$cnt[$nums[$i + 1]]++;
if ($mx < $cnt[$nums[$i + 1]]) {
$mx = $cnt[$nums[$i + 1]];
$ans = $nums[$i + 1];
}
}
}
return $ans;
}
}
2215. Find the Difference of Two Arrays
JuniorDescription: Solve the LeetCode challenge "find-the-difference-of-two-arrays" using PHP.
Code:
class Solution {
/**
* @param Integer[] $nums1
* @param Integer[] $nums2
* @return Integer[][]
*/
function findDifference($nums1, $nums2) {
$s1 = array_flip($nums1);
$s2 = array_flip($nums2);
$diff1 = array_diff_key($s1, $s2);
$diff2 = array_diff_key($s2, $s1);
return [array_keys($diff1), array_keys($diff2)];
}
}
2248. Intersection of Multiple Arrays
JuniorDescription: Solve the LeetCode challenge "intersection-of-multiple-arrays" using PHP.
Code:
class Solution {
/**
* @param Integer[][] $nums
* @return Integer[]
*/
function intersection($nums) {
$rs = [];
for ($i = 0; $i < count($nums); $i++) {
for ($j = 0; $j < count($nums[$i]); $j++) {
$hashtable[$nums[$i][$j]] += 1;
if ($hashtable[$nums[$i][$j]] === count($nums)) {
array_push($rs, $nums[$i][$j]);
}
}
}
sort($rs);
return $rs;
}
}
2259. Remove Digit From Number to Maximize Result
JuniorDescription: Solve the LeetCode challenge "remove-digit-from-number-to-maximize-result" using PHP.
Code:
class Solution {
/**
* @param String $number
* @param String $digit
* @return String
*/
function removeDigit($number, $digit) {
$max = 0;
for ($i = 0; $i < strlen($number); $i++) {
if ($number[$i] == $digit) {
$tmp = substr($number, 0, $i) . substr($number, $i + 1);
if ($tmp > $max) {
$max = $tmp;
}
}
}
return $max;
}
}
2351. First Letter to Appear Twice
JuniorDescription: Solve the LeetCode challenge "first-letter-to-appear-twice" using PHP.
Code:
class Solution {
/**
* @param String $s
* @return String
*/
function repeatedCharacter($s) {
for ($i = 0; ; $i++) {
$hashtable[$s[$i]] += 1;
if ($hashtable[$s[$i]] == 2) {
return $s[$i];
}
}
}
}
2379. Minimum Recolors to Get K Consecutive Black Blocks
JuniorDescription: Solve the LeetCode challenge "minimum-recolors-to-get-k-consecutive-black-blocks" using PHP.
Code:
class Solution {
/**
* @param String $blocks
* @param Integer $k
* @return Integer
*/
function minimumRecolors($blocks, $k) {
$cnt = 0;
for ($i = 0; $i < $k; $i++) {
if ($blocks[$i] === 'W') {
$cnt++;
}
}
$min = $cnt;
for ($i = $k; $i < strlen($blocks); $i++) {
if ($blocks[$i] === 'W') {
$cnt++;
}
if ($blocks[$i - $k] === 'W') {
$cnt--;
}
$min = min($min, $cnt);
}
return $min;
}
}
2404. Most Frequent Even Element
JuniorDescription: Solve the LeetCode challenge "most-frequent-even-element" using PHP.
Code:
class Solution {
/**
* @param Integer[] $nums
* @return Integer
*/
function mostFrequentEven($nums) {
$max = $rs = -1;
for ($i = 0; $i < count($nums); $i++) {
if ($nums[$i] % 2 == 0) {
$hashtable[$nums[$i]] += 1;
if (
$hashtable[$nums[$i]] > $max ||
($hashtable[$nums[$i]] == $max && $rs > $nums[$i])
) {
$max = $hashtable[$nums[$i]];
$rs = $nums[$i];
}
}
}
return $rs;
}
}
2485. Find the Pivot Integer
JuniorDescription: Solve the LeetCode challenge "find-the-pivot-integer" using PHP.
Code:
class Solution {
/**
* @param Integer $n
* @return Integer
*/
function pivotInteger($n) {
$sum = ($n * ($n + 1)) / 2;
$pre = 0;
for ($i = 1; $i <= $n; $i++) {
if ($pre + $i === $sum - $pre) {
return $i;
}
$pre += $i;
}
return -1;
}
}
94. Binary Tree Inorder Traversal
JuniorDescription:
Given the root of a binary tree, return the inorder traversal of its nodes' values.
Example 1:
Input: root = [1,null,2,3]
Output: [1,3,2]
Explanation:
Example 2:
Input: root = [1,2,3,4,5,null,8,null,null,6,7,9]
Output: [4,2,6,5,7,1,3,9,8]
Explanation:
Example 3:
Input: root = []
Output: []
Example 4:
Input: root = [1]
Output: [1]
Constraints:
- The number of nodes in the tree is in the range
[0, 100]. -100 <= Node.val <= 100
Follow up: Recursive solution is trivial, could you do it iteratively?
Code:
// PHP solution for this challenge is currently being updated.
111. Minimum Depth of Binary Tree
JuniorDescription:
Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
Note: A leaf is a node with no children.
Example 1:
Input: root = [3,9,20,null,null,15,7]
Output: 2
Example 2:
Input: root = [2,null,3,null,4,null,5,null,6]
Output: 5
Constraints:
- The number of nodes in the tree is in the range
[0, 10^5]. -1000 <= Node.val <= 1000
Code:
// PHP solution for this challenge is currently being updated.
141. Linked List Cycle
JuniorDescription:
Given head, the head of a linked list, determine if the linked list has a cycle in it.
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to. Note that pos is not passed as a parameter.
Return true_ if there is a cycle in the linked list_. Otherwise, return false.
Example 1:
Input: head = [3,2,0,-4], pos = 1
Output: true
Explanation: There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).
Example 2:
Input: head = [1,2], pos = 0
Output: true
Explanation: There is a cycle in the linked list, where the tail connects to the 0th node.
Example 3:
Input: head = [1], pos = -1
Output: false
Explanation: There is no cycle in the linked list.
Constraints:
- The number of the nodes in the list is in the range
[0, 10^4]. -10^5 <= Node.val <= 10^5posis-1or a valid index in the linked-list.
Follow up: Can you solve it using O(1) (i.e. constant) memory?
Code:
// PHP solution for this challenge is currently being updated.
144. Binary Tree Preorder Traversal
JuniorDescription:
Given the root of a binary tree, return the preorder traversal of its nodes' values.
Example 1:
Input: root = [1,null,2,3]
Output: [1,2,3]
Explanation:
Example 2:
Input: root = [1,2,3,4,5,null,8,null,null,6,7,9]
Output: [1,2,4,5,6,7,3,8,9]
Explanation:
Example 3:
Input: root = []
Output: []
Example 4:
Input: root = [1]
Output: [1]
Constraints:
- The number of nodes in the tree is in the range
[0, 100]. -100 <= Node.val <= 100
Follow up: Recursive solution is trivial, could you do it iteratively?
Code:
// PHP solution for this challenge is currently being updated.
145. Binary Tree Postorder Traversal
JuniorDescription:
Given the root of a binary tree, return the postorder traversal of its nodes' values.
Example 1:
Input: root = [1,null,2,3]
Output: [3,2,1]
Explanation:
Example 2:
Input: root = [1,2,3,4,5,null,8,null,null,6,7,9]
Output: [4,6,7,5,2,9,8,3,1]
Explanation:
Example 3:
Input: root = []
Output: []
Example 4:
Input: root = [1]
Output: [1]
Constraints:
- The number of the nodes in the tree is in the range
[0, 100]. -100 <= Node.val <= 100
Follow up: Recursive solution is trivial, could you do it iteratively?
Code:
// PHP solution for this challenge is currently being updated.
206. Reverse Linked List
JuniorDescription:
Given the head of a singly linked list, reverse the list, and return the reversed list.
Example 1:
Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]
Example 2:
Input: head = [1,2]
Output: [2,1]
Example 3:
Input: head = []
Output: []
Constraints:
- The number of nodes in the list is the range
[0, 5000]. -5000 <= Node.val <= 5000
Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both?
Code:
// PHP solution for this challenge is currently being updated.
222. Count Complete Tree Nodes
JuniorDescription:
Given the root of a complete binary tree, return the number of the nodes in the tree.
According to Wikipedia, every level, except possibly the last, is completely filled in a complete binary tree, and all nodes in the last level are as far left as possible. It can have between 1 and 2^h nodes inclusive at the last level h.
Design an algorithm that runs in less than O(n) time complexity.
Example 1:
Input: root = [1,2,3,4,5,6]
Output: 6
Example 2:
Input: root = []
Output: 0
Example 3:
Input: root = [1]
Output: 1
Constraints:
- The number of nodes in the tree is in the range
[0, 5 * 10^4]. 0 <= Node.val <= 5 * 10^4- The tree is guaranteed to be complete.
Code:
// PHP solution for this challenge is currently being updated.
231. Power of Two
JuniorDescription:
Given an integer n, return true if it is a power of two. Otherwise, return false.
An integer n is a power of two, if there exists an integer x such that n == 2^x.
Example 1:
Input: n = 1
Output: true
Explanation: 2^0 = 1
Example 2:
Input: n = 16
Output: true
Explanation: 2^4 = 16
Example 3:
Input: n = 3
Output: false
Constraints:
-2^31 <= n <= 2^31 - 1
Follow up: Could you solve it without loops/recursion?
Code:
// PHP solution for this challenge is currently being updated.
270. Closest Binary Search Tree Value 🔒
JuniorDescription:
Given the root of a binary search tree and a target value, return the value in the BST that is closest to the target. If there are multiple answers, print the smallest.
Example 1:
Input: root = [4,2,5,1,3], target = 3.714286
Output: 4
Example 2:
Input: root = [1], target = 4.428571
Output: 1
Constraints:
- The number of nodes in the tree is in the range
[1, 10^4]. 0 <= Node.val <= 10^9-10^9 <= target <= 10^9
Code:
// PHP solution for this challenge is currently being updated.
326. Power of Three
JuniorDescription:
Given an integer n, return true if it is a power of three. Otherwise, return false.
An integer n is a power of three, if there exists an integer x such that n == 3^x.
Example 1:
Input: n = 27
Output: true
Explanation: 27 = 3^3
Example 2:
Input: n = 0
Output: false
Explanation: There is no x where 3^x = 0.
Example 3:
Input: n = -1
Output: false
Explanation: There is no x where 3^x = (-1).
Constraints:
-2^31 <= n <= 2^31 - 1
Follow up: Could you solve it without loops/recursion?
Code:
// PHP solution for this challenge is currently being updated.
346. Moving Average from Data Stream 🔒
JuniorDescription:
Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.
Implement the MovingAverage class:
MovingAverage(int size)Initializes the object with the size of the windowsize.double next(int val)Returns the moving average of the lastsizevalues of the stream.
Example 1:
Input
["MovingAverage", "next", "next", "next", "next"]
[[3], [1], [10], [3], [5]]
Output
[null, 1.0, 5.5, 4.66667, 6.0]
Explanation
MovingAverage movingAverage = new MovingAverage(3);
movingAverage.next(1); // return 1.0 = 1 / 1
movingAverage.next(10); // return 5.5 = (1 + 10) / 2
movingAverage.next(3); // return 4.66667 = (1 + 10 + 3) / 3
movingAverage.next(5); // return 6.0 = (10 + 3 + 5) / 3
Constraints:
1 <= size <= 1000-10^5 <= val <= 10^5- At most
10^4calls will be made tonext.
Code:
// PHP solution for this challenge is currently being updated.