561. Array Partition I [Leetcode]

https://leetcode.com/problems/array-partition-i/submissions/

Given an integer array nums of 2n integers, group these integers into n pairs (a1, b1), (a2, b2), ..., (an, bn) such that the sum of min(ai, bi) for all i is maximized. Return the maximized sum.

Example 1:

Input: nums = [1,4,3,2]
Output: 4
Explanation: All possible pairings (ignoring the ordering of elements) are:
1. (1, 4), (2, 3) -> min(1, 4) + min(2, 3) = 1 + 2 = 3
2. (1, 3), (2, 4) -> min(1, 3) + min(2, 4) = 1 + 2 = 3
3. (1, 2), (3, 4) -> min(1, 2) + min(3, 4) = 1 + 3 = 4
So the maximum possible sum is 4.

Example 2:

Input: nums = [6,2,6,5,1,2]
Output: 9
Explanation: The optimal pairing is (2, 1), (2, 5), (6, 6). min(2, 1) + min(2, 5) + min(6, 6) = 1 + 2 + 6 = 9.

Constraints:

  • 1 <= n <= 104
  • nums.length == 2 * n
  • -104 <= nums[i] <= 104

Solution:

/**
 * https://leetcode.com/problems/array-partition-i
 * github: theketan2
 * @param {number[]} nums
 * @return {number}
 */
var arrayPairSum = function (nums) {
  nums.sort((a, b) => parseInt(a) - parseInt(b));
  let sol = 0;
  console.log(nums);
  for (let i = 0; i < nums.length; i += 2) {
    sol += nums[i];
  }
  return sol;
};

492. Construct the Rectangle[Leetcode]

Leetcode

A web developer needs to know how to design a web page’s size. So, given a specific rectangular web page’s area, your job by now is to design a rectangular web page, whose length L and width W satisfy the following requirements:

  1. The area of the rectangular web page you designed must equal to the given target area.
  2. The width W should not be larger than the length L, which means L >= W.
  3. The difference between length L and width W should be as small as possible.

Return an array [L, W] where L and W are the length and width of the web page you designed in sequence.

Example 1:

Input: area = 4
Output: [2,2]
Explanation: The target area is 4, and all the possible ways to construct it are [1,4], [2,2], [4,1]. 
But according to requirement 2, [1,4] is illegal; according to requirement 3,  [4,1] is not optimal compared to [2,2]. So the length L is 2, and the width W is 2.

Example 2:

Input: area = 37
Output: [37,1]

Example 3:

Input: area = 122122
Output: [427,286]

Constraints:

  • 1 <= area <= 107

Solution:

/**
 * https://leetcode.com/problems/construct-the-rectangle/
 * github: theketan2
 * @param {number} area
 * @return {number[]}
 */
var constructRectangle = function (area) {
  let diff = 9999999999;
  let solArr = [];
  for (let i = 1; i <= Math.ceil(area / 2); i++) {
    let remainder = area % i;
    if (remainder === 0) {
      let div = area / i;
      let tempDiff = Math.abs(i - div);
      if (tempDiff < diff) {
        let min = i < div ? i : div;
        let max = i > div ? i : div;
        solArr = [max, min];
        diff = tempDiff;
      }
    }
  }
  return solArr;
};

1446. Consecutive Characters [Leetcode]

Leetcode

Given a string s, the power of the string is the maximum length of a non-empty substring that contains only one unique character.

Return the power of the string.

Example 1:

Input: s = "leetcode"
Output: 2
Explanation: The substring "ee" is of length 2 with the character 'e' only.

Example 2:

Input: s = "abbcccddddeeeeedcba"
Output: 5
Explanation: The substring "eeeee" is of length 5 with the character 'e' only.

Example 3:

Input: s = "triplepillooooow"
Output: 5

Example 4:

Input: s = "hooraaaaaaaaaaay"
Output: 11

Example 5:

Input: s = "tourist"
Output: 1

Constraints:

  • 1 <= s.length <= 500
  • s contains only lowercase English letters.

Solution:

/**
 * https://leetcode.com/problems/consecutive-characters
 * github: theketan2
 * @param {string} s
 * @return {number}
 */
var maxPower = function(s) {
    let max = 0, temp = 1;
    for(let i = 1; i<s.length; i++){
      if(s[i-1] == s[i]){
        temp++;
      }else{
        if(max<temp)
          max = temp;
        temp = 1;
      }
    }
  if(max<temp)
    max = temp
  console.log(max)
  return max;
};

First N Mid [Edabit]

Edabit

Create a function that takes a string and returns the first character of every word if the length of the word is even and the middle character if the length of the word is odd.

Examples

stmid("Alexa have to paid") ➞ "ehtp"
// "e" is the middle character of "Alexa"
// "h" is the first character of "have"

stmid("Th3 0n3 4nd 0n1y") ➞ "hnn0"

stmid("who is the winner") ➞ "hihw"

Solution:

function stmid(str) {
  return str
    .split(" ")
    .map((word) =>
      word.length % 2 === 0 ? word[0] : word[Math.floor(word.length / 2)]
    )
    .join("");
}

1441. Build an Array With Stack Operations[Leetcode]

Leetcode

Given an array target and an integer n. In each iteration, you will read a number from  list = {1,2,3..., n}.

Build the target array using the following operations:

  • Push: Read a new element from the beginning list, and push it in the array.
  • Pop: delete the last element of the array.
  • If the target array is already built, stop reading more elements.

You are guaranteed that the target array is strictly increasing, only containing numbers between 1 to n inclusive.

Return the operations to build the target array.

You are guaranteed that the answer is unique.

Example 1:

Input: target = [1,3], n = 3
Output: ["Push","Push","Pop","Push"]
Explanation: 
Read number 1 and automatically push in the array -> [1]
Read number 2 and automatically push in the array then Pop it -> [1]
Read number 3 and automatically push in the array -> [1,3]

Example 2:

Input: target = [1,2,3], n = 3
Output: ["Push","Push","Push"]

Example 3:

Input: target = [1,2], n = 4
Output: ["Push","Push"]
Explanation: You only need to read the first 2 numbers and stop.

Example 4:

Input: target = [2,3,4], n = 4
Output: ["Push","Pop","Push","Push","Push"]

Constraints:

  • 1 <= target.length <= 100
  • 1 <= target[i] <= 100
  • 1 <= n <= 100
  • target is strictly increasing.

Solution:

/**
 * https://leetcode.com/problems/build-an-array-with-stack-operations/
 * github: theketan2
 * @param {number[]} target
 * @param {number} n
 * @return {string[]}
 */
var buildArray = function (target, n) {
  let arr = [];
  for (let i = 1; i <= target[target.length - 1]; i++) {
    arr.push("Push");
    if (!target.includes(i)) arr.push("Pop");
  }
  return arr;
};

Maximum Travel Distance [Edabit]

Edbit

Write a function that takes fuel (liters), fuelUsage (liters/100km), passengersairCon (boolean) and returns maximum distance that car can travel.

  • fuel is the number of liters of fuel in the fuel tank.
  • fuelUsage is basic fuel consumption per 100 km (with the driver inside only).
  • Every additional passenger is increasing basic fuel consumption by 5%.
  • If the air conditioner is ON true, its increasing total (not basic) fuel consumption by 10%.

Examples

totalDistance(70.0, 7.0, 0, false) ➞ 1000.0

totalDistance(36.1, 8.6, 3, true) ➞ 331.8

totalDistance(55.5, 5.5, 5, false) ➞ 807.3

Notes

  • fuel and fuelUsage are always greater than 1.
  • passengers are always greater or equal to 0.
  • Round your answer to the nearest tenth.

Solution:

function totalDistance(fuel, fuelUsage, passengers, airCon) {
	fuelUsage += (fuelUsage* (passengers * 0.05))
	if(airCon){
		fuelUsage += (fuelUsage * 0.1)
	}
	return Number(((fuel / fuelUsage) * 100).toFixed(1))
}

1608. Special Array With X Elements Greater Than or Equal [Leetcode]

Leetcode

You are given an array nums of non-negative integers. nums is considered special if there exists a number x such that there are exactly x numbers in nums that are greater than or equal to x.

Notice that x does not have to be an element in nums.

Return x if the array is special, otherwise, return -1. It can be proven that if nums is special, the value for x is unique.

Example 1:

Input: nums = [3,5]
Output: 2
Explanation: There are 2 values (3 and 5) that are greater than or equal to 2.

Example 2:

Input: nums = [0,0]
Output: -1
Explanation: No numbers fit the criteria for x.
If x = 0, there should be 0 numbers >= x, but there are 2.
If x = 1, there should be 1 number >= x, but there are 0.
If x = 2, there should be 2 numbers >= x, but there are 0.
x cannot be greater since there are only 2 numbers in nums.

Example 3:

Input: nums = [0,4,3,0,4]
Output: 3
Explanation: There are 3 values that are greater than or equal to 3.

Example 4:

Input: nums = [3,6,7,7,0]
Output: -1

Constraints:

  • 1 <= nums.length <= 100
  • 0 <= nums[i] <= 1000

Solution:

/**
 * https://leetcode.com/problems/special-array-with-x-elements-greater-than-or-equal-x
 * github: theketan2
 * @param {number[]} nums
 * @return {number}
 */
var specialArray = function (nums) {
  let max = Math.max(...nums);
  let luckyNum = -1;
  for (let i = 0; i <= max; i++) {
    let len = nums.filter((num) => num >= i).length;
    console.log(len);
    if (i === len) {
      luckyNum = i;
    }
  }
  return luckyNum;
};

App for searching nation from the given list of countries using Flutter.

Screenshot of final app:

Github Repo

Full Source code:

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List fullTaskDetailsList = [];
  List taskDetailsList = [];
  TextEditingController mycontroller = TextEditingController();

  void searchMethodWithTest(String text) {
    List result = [];
    print("Text: " + text.length.toString());
    if (mycontroller.text.isNotEmpty) {
      fullTaskDetailsList.forEach((element) {
        text = text.trim();
        if (element.toLowerCase().contains(text)) {
          result.add(element);
        }
      });
      print(taskDetailsList.toString());
      setState(() {
        taskDetailsList = result;
      });
      return;
    } else {
      setState(() {
        taskDetailsList = fullTaskDetailsList;
      });
      return;
    }
  }

  @override
  void initState() {
    fullTaskDetailsList = countryList;
    taskDetailsList = fullTaskDetailsList;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: SingleChildScrollView(
        child: Center(
          child: Column(
            children: [
              TextField(
                controller: mycontroller,
                onChanged: (value) {
                  searchMethodWithTest(mycontroller.text.toLowerCase());
                },
                decoration: InputDecoration(
                  contentPadding: EdgeInsets.all(10),
                  hintText: "Search For Countries",
                ),
              ),
              Text("Searched for: ${mycontroller.text}"),
              Container(
                width: double.infinity,
                height: 400.0,
                child: ListView.builder(
                    itemCount: taskDetailsList.length,
                    itemBuilder: (context, index) {
                      return ListTile(
                        title: Text(
                          taskDetailsList[index],
                          style: TextStyle(
                            fontSize: 20.0,
                          ),
                        ),
                      );
                    }),
              )
            ],
          ),
        ),
      ),
      // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

const countryList = [
  "Afghanistan",
  "Albania",
  "Algeria",
  "American Samoa",
  "Andorra",
  "Angola",
  "Anguilla",
  "Antarctica",
  "Antigua and Barbuda",
  "Argentina",
  "Armenia",
  "Aruba",
  "Australia",
  "Austria",
  "Azerbaijan",
  "Bahamas (the)",
  "Bahrain",
  "Bangladesh",
  "Barbados",
  "Belarus",
  "Belgium",
  "Belize",
  "Benin",
  "Bermuda",
  "Bhutan",
  "Bolivia (Plurinational State of)",
  "Bonaire, Sint Eustatius and Saba",
  "Bosnia and Herzegovina",
  "Botswana",
  "Bouvet Island",
  "Brazil",
  "British Indian Ocean Territory (the)",
  "Brunei Darussalam",
  "Bulgaria",
  "Burkina Faso",
  "Burundi",
  "Cabo Verde",
  "Cambodia",
  "Cameroon",
  "Canada",
  "Cayman Islands (the)",
  "Central African Republic (the)",
  "Chad",
  "Chile",
  "China",
  "Christmas Island",
  "Cocos (Keeling) Islands (the)",
  "Colombia",
  "Comoros (the)",
  "Congo (the Democratic Republic of the)",
  "Congo (the)",
  "Cook Islands (the)",
  "Costa Rica",
  "Croatia",
  "Cuba",
  "Curaçao",
  "Cyprus",
  "Czechia",
  "Côte d'Ivoire",
  "Denmark",
  "Djibouti",
  "Dominica",
  "Dominican Republic (the)",
  "Ecuador",
  "Egypt",
  "El Salvador",
  "Equatorial Guinea",
  "Eritrea",
  "Estonia",
  "Eswatini",
  "Ethiopia",
  "Falkland Islands (the) [Malvinas]",
  "Faroe Islands (the)",
  "Fiji",
  "Finland",
  "France",
  "French Guiana",
  "French Polynesia",
  "French Southern Territories (the)",
  "Gabon",
  "Gambia (the)",
  "Georgia",
  "Germany",
  "Ghana",
  "Gibraltar",
  "Greece",
  "Greenland",
  "Grenada",
  "Guadeloupe",
  "Guam",
  "Guatemala",
  "Guernsey",
  "Guinea",
  "Guinea-Bissau",
  "Guyana",
  "Haiti",
  "Heard Island and McDonald Islands",
  "Holy See (the)",
  "Honduras",
  "Hong Kong",
  "Hungary",
  "Iceland",
  "India",
  "Indonesia",
  "Iran (Islamic Republic of)",
  "Iraq",
  "Ireland",
  "Isle of Man",
  "Israel",
  "Italy",
  "Jamaica",
  "Japan",
  "Jersey",
  "Jordan",
  "Kazakhstan",
  "Kenya",
  "Kiribati",
  "Korea (the Democratic People's Republic of)",
  "Korea (the Republic of)",
  "Kuwait",
  "Kyrgyzstan",
  "Lao People's Democratic Republic (the)",
  "Latvia",
  "Lebanon",
  "Lesotho",
  "Liberia",
  "Libya",
  "Liechtenstein",
  "Lithuania",
  "Luxembourg",
  "Macao",
  "Madagascar",
  "Malawi",
  "Malaysia",
  "Maldives",
  "Mali",
  "Malta",
  "Marshall Islands (the)",
  "Martinique",
  "Mauritania",
  "Mauritius",
  "Mayotte",
  "Mexico",
  "Micronesia (Federated States of)",
  "Moldova (the Republic of)",
  "Monaco",
  "Mongolia",
  "Montenegro",
  "Montserrat",
  "Morocco",
  "Mozambique",
  "Myanmar",
  "Namibia",
  "Nauru",
  "Nepal",
  "Netherlands (the)",
  "New Caledonia",
  "New Zealand",
  "Nicaragua",
  "Niger (the)",
  "Nigeria",
  "Niue",
  "Norfolk Island",
  "Northern Mariana Islands (the)",
  "Norway",
  "Oman",
  "Pakistan",
  "Palau",
  "Palestine, State of",
  "Panama",
  "Papua New Guinea",
  "Paraguay",
  "Peru",
  "Philippines (the)",
  "Pitcairn",
  "Poland",
  "Portugal",
  "Puerto Rico",
  "Qatar",
  "Republic of North Macedonia",
  "Romania",
  "Russian Federation (the)",
  "Rwanda",
  "Réunion",
  "Saint Barthélemy",
  "Saint Helena, Ascension and Tristan da Cunha",
  "Saint Kitts and Nevis",
  "Saint Lucia",
  "Saint Martin (French part)",
  "Saint Pierre and Miquelon",
  "Saint Vincent and the Grenadines",
  "Samoa",
  "San Marino",
  "Sao Tome and Principe",
  "Saudi Arabia",
  "Senegal",
  "Serbia",
  "Seychelles",
  "Sierra Leone",
  "Singapore",
  "Sint Maarten (Dutch part)",
  "Slovakia",
  "Slovenia",
  "Solomon Islands",
  "Somalia",
  "South Africa",
  "South Georgia and the South Sandwich Islands",
  "South Sudan",
  "Spain",
  "Sri Lanka",
  "Sudan (the)",
  "Suriname",
  "Svalbard and Jan Mayen",
  "Sweden",
  "Switzerland",
  "Syrian Arab Republic",
  "Taiwan",
  "Tajikistan",
  "Tanzania, United Republic of",
  "Thailand",
  "Timor-Leste",
  "Togo",
  "Tokelau",
  "Tonga",
  "Trinidad and Tobago",
  "Tunisia",
  "Turkey",
  "Turkmenistan",
  "Turks and Caicos Islands (the)",
  "Tuvalu",
  "Uganda",
  "Ukraine",
  "United Arab Emirates (the)",
  "United Kingdom of Great Britain and Northern Ireland (the)",
  "United States Minor Outlying Islands (the)",
  "United States of America (the)",
  "Uruguay",
  "Uzbekistan",
  "Vanuatu",
  "Venezuela (Bolivarian Republic of)",
  "Viet Nam",
  "Virgin Islands (British)",
  "Virgin Islands (U.S.)",
  "Wallis and Futuna",
  "Western Sahara",
  "Yemen",
  "Zambia",
  "Zimbabwe",
  "Åland Islands"
];

1572. Matrix Diagonal Sum[Leetcode]

Leetcode

  • n == mat.length == mat[i].length
  • 1 <= n <= 100
  • 1 <= mat[i][j] <= 100

Solution:

/**
 * https://leetcode.com/problems/matrix-diagonal-sum/
 * github: theketan2
 * @param {number[][]} mat
 * @return {number}
 */
var diagonalSum = function (mat) {
  let sum = 0;
  for (let i = 0, j = 0, k = mat.length - 1; i < mat.length; i++, j++, k--) {
    sum += mat[i][j];
    sum += mat[k][j];
  }
  if (mat.length % 2 === 0) return sum;
  let index = Math.floor(mat.length / 2);
  return sum - mat[index][index];
};

Find the Characters Counterpart Char Code [Edabit]

Edabit

Create a function that takes a single character as an argument and returns the char code of its lowercased / uppercased counterpart.

Examples

Given that:
  - "A" char code is: 65
  - "a" char code is: 97

counterpartCharCode("A") ➞ 97

counterpartCharCode("a") ➞ 65

Notes

  • The argument will always be a single character.
  • Not all inputs will have a counterpart (e.g. numbers), in which case return the inputs char code.

Solution:

function counterpartCharCode(char) {
  return char === char.toUpperCase()
    ? char.toLowerCase().charCodeAt()
    : char.toUpperCase().charCodeAt();
}