NotesWhat is notes.io?

Notes brand slogan

Notes - notes.io



Question: 1
String Compression :You are given a string s. Your task is to compress the string such that consecutive characters are replaced by the character followed by the number of times it appears consecutively.If the compressed string is not smaller than the original string, return the original string.

Input: "aabcccccaaa"
Output: "a2b1c5a3"

Input: "abcd"
Output: "abcd"

Solution:
function compressString(s) {
if (s.length === 1) return s;
let result = '';
let count = 1;
for (let i = 1; i <= s.length; i++) {
if (s[i] === s[i - 1]) {
count++;
} else {
result += s[i - 1] + count;
count = 1;
}
}
return result.length < s.length ? result : s;
}

============================================================================================================
Question 2:
Transpose-matrix : Given a 2D integer array matrix, return the transpose of matrix.
The transpose of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices.

Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [[1,4,7],[2,5,8],[3,6,9]]

Input: matrix = [[1,2,3],[4,5,6]]
Output: [[1,4],[2,5],[3,6]]
Solution:
var transpose = function(matrix) {
const row = matrix.length;
const col = matrix[0].length;
const ans = new Array(col).fill(0).map(() => new Array(row).fill(0));
for (let i = 0; i < row; i++)
for (let j = 0; j < col; j++)
ans[j][i] = matrix[i][j];
return ans;
}
============================================================================================================

Question 3
Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value.
If target is not found in the array, return [-1, -1].
You must write an algorithm with O(log n) runtime complexity.

Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]
Input: nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1]
Input: nums = [], target = 0
Output: [-1,-1]

Solution:
var searchRange = function(nums, target) {
if (nums.length === 0) return [-1, -1]
let left = 0
let right = nums.length - 1
let res = []

while (left <= right) {
const mid = left + parseInt((right - left)/2)
if (nums[mid] < target) left = mid + 1
else if (nums[mid] > target) right = mid - 1
else if (nums[mid] === target) {
let i = mid
while (nums[i] === target) i--
res.push(i+1)
let j = mid
while (nums[j+1] === target) j++
res.push(j)
return res;
}
}
return [-1, -1]
};

============================================================================================================
Question 4 : Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array.
Input: nums = [3,0,1]
Output: 2
Input: nums = [0,1]
Output: 2
Input: nums = [9,6,4,2,3,5,7,0,1]
Output: 8

solution:

var missingNumber = function(nums) {
const n = nums.length;
const Tsum = (n * (n + 1)) / 2;
const actualSum = nums.reduce((acc, num) => acc + num, 0);
return Tsum - actualSum;
};

============================================================================================================
Question 5 : Given a string s, return the first word that appears more than once in the string. The words in the string are separated by spaces, and you should treat the comparison as case-sensitive.
If no word is repeated, return null.
Input: "this is a test sentence with a repeated word"
Output: "a"

Input: "hello world hello"
output: "hello"

input: "unique words no repetitions"
output: null

Solution :
function firstRepeatedWord(str) {
const words = str.split(/s+/);
const seenWords = new Set();

for (let i = 0; i < words.length; i++) {
const word = words[i]; // Get the word

if (seenWords.has(word)) {
return word; // First repeated word found
}

seenWords.add(word);
}

return null;
}

// Example usage:
console.log(firstRepeatedWord("this is a test sentence with a repeated word")); // Output: "a"
console.log(firstRepeatedWord("hello world hello")); // Output: "hello"
console.log(firstRepeatedWord("unique words no repetitions")); // Output: null

============================================================================================================

Question 6: Find the Longest Substring Without Repeating Characters
Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3

Input: s = "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1

Input: s = "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.

Solution
var lengthOfLongestSubstring = function (s) {
let set = new Set();
let left = 0;
let maxSize = 0;

if (s.length === 0) return 0;
if (s.length === 1) return 1;

for (let i = 0; i < s.length; i++) {

while (set.has(s[i])) {
set.delete(s[left])
left++;
}
set.add(s[i]);
maxSize = Math.max(maxSize, i - left + 1)
}
return maxSize;
}
============================================================================================================
Question 7 : Valid Parentheses
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

An input string is valid if:

Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Every close bracket has a corresponding open bracket of the same type

Input: s = "()"
Output: true

Input: s = "()[]{}"
Output: true

Input: s = "(]"
Output: false

Solution:
function isValid(s) {
const stack = [];
const map = {
')': '(',
'}': '{',
']': '['
};

for (let i = 0; i < s.length; i++) {
const char = s[i];

// If the character is a closing bracket
if (map[char]) {
// Check if the stack is empty or the top of the stack doesn't match the opening bracket
if (stack.pop() !== map[char]) {
return false;
}
} else {
// If it's an opening bracket, push it to the stack
stack.push(char);
}
}

// If the stack is empty, all brackets were matched
return stack.length === 0;
}

// Example usage:
console.log(isValid("()")); // Output: true
console.log(isValid("()[]{}")); // Output: true
console.log(isValid("(]")); // Output: false
console.log(isValid("([)]")); // Output: false
console.log(isValid("{[]}")); // Output: true

     
 
what is notes.io
 

Notes is a web-based application for online taking notes. You can take your notes and share with others people. If you like taking long notes, notes.io is designed for you. To date, over 8,000,000,000+ notes created and continuing...

With notes.io;

  • * You can take a note from anywhere and any device with internet connection.
  • * You can share the notes in social platforms (YouTube, Facebook, Twitter, instagram etc.).
  • * You can quickly share your contents without website, blog and e-mail.
  • * You don't need to create any Account to share a note. As you wish you can use quick, easy and best shortened notes with sms, websites, e-mail, or messaging services (WhatsApp, iMessage, Telegram, Signal).
  • * Notes.io has fabulous infrastructure design for a short link and allows you to share the note as an easy and understandable link.

Fast: Notes.io is built for speed and performance. You can take a notes quickly and browse your archive.

Easy: Notes.io doesn’t require installation. Just write and share note!

Short: Notes.io’s url just 8 character. You’ll get shorten link of your note when you want to share. (Ex: notes.io/q )

Free: Notes.io works for 14 years and has been free since the day it was started.


You immediately create your first note and start sharing with the ones you wish. If you want to contact us, you can use the following communication channels;


Email: [email protected]

Twitter: http://twitter.com/notesio

Instagram: http://instagram.com/notes.io

Facebook: http://facebook.com/notesio



Regards;
Notes.io Team

     
 
Shortened Note Link
 
 
Looding Image
 
     
 
Long File
 
 

For written notes was greater than 18KB Unable to shorten.

To be smaller than 18KB, please organize your notes, or sign in.