SkylineWebZ

Length of Last Word In C,CPP,JAVA,PYTHON,C#,JS

The “Length of Last Word“ problem is a classic problem often asked in coding interviews. The task is to determine the length of the last word in a given string. A word is defined as a sequence of non-space characters, and the words in the string are separated by spaces. Problem Statement: Given a string s, return the length of the last word in it. Example: Input: “Hello World” Output: 5 Explanation: The last word is “World”, and its length is 5. Input: arduinoCopy code” fly me to the moon ” Output: 4 Explanation: The last word is “moon”, and its length is 4. Input: “luffy is still joyboy” Output: 6 Explanation: The last word is “joyboy”, and its length is 6. Approach: We can solve this problem in two main ways: Solution Approach 1: Iteration from the end Solution Approach 2: Using built-in functions (trim, split) Code Implementations: 1. C++ #include <iostream>#include <string>#include <algorithm>using namespace std;int lengthOfLastWord(string s) { int n = s.length(); int length = 0; // Start from the end of the string int i = n – 1; // Skip trailing spaces while (i >= 0 && s[i] == ‘ ‘) { i–; } // Count the length of the last word while (i >= 0 && s[i] != ‘ ‘) { length++; i–; } return length;}int main() { string str = “Hello World”; cout << “Length of last word: ” << lengthOfLastWord(str) << endl; // Output: 5 return 0;} 2. C #include <stdio.h>#include <string.h>int lengthOfLastWord(char *s) { int len = strlen(s); int length = 0; // Skip trailing spaces while (len > 0 && s[len – 1] == ‘ ‘) { len–; } // Count the length of the last word while (len > 0 && s[len – 1] != ‘ ‘) { length++; len–; } return length;}int main() { char str[] = “Hello World”; printf(“Length of last word: %d\n”, lengthOfLastWord(str)); // Output: 5 return 0;} 3. Java public class LengthOfLastWord { public int lengthOfLastWord(String s) { int length = 0; int n = s.length(); // Skip trailing spaces int i = n – 1; while (i >= 0 && s.charAt(i) == ‘ ‘) { i–; } // Count the length of the last word while (i >= 0 && s.charAt(i) != ‘ ‘) { length++; i–; } return length; } public static void main(String[] args) { LengthOfLastWord solution = new LengthOfLastWord(); String str = “Hello World”; System.out.println(“Length of last word: ” + solution.lengthOfLastWord(str)); // Output: 5 }} 4. Python def lengthOfLastWord(s: str) -> int: s = s.strip() # Remove leading/trailing spaces words = s.split() # Split the string into words return len(words[-1]) # Return the length of the last word# Test the functionprint(lengthOfLastWord(“Hello World”)) # Output: 5 5. C# using System;public class Solution { public int LengthOfLastWord(string s) { s = s.Trim(); // Remove leading/trailing spaces string[] words = s.Split(); // Split the string into words return words[words.Length – 1].Length; // Return the length of the last word } public static void Main() { Solution solution = new Solution(); string str = “Hello World”; Console.WriteLine(solution.LengthOfLastWord(str)); // Output: 5 }} 6. JavaScript function lengthOfLastWord(s) { s = s.trim(); // Remove leading/trailing spaces const words = s.split(‘ ‘); // Split the string into words return words[words.length – 1].length; // Return the length of the last word}// Test the functionconsole.log(lengthOfLastWord(“Hello World”)); // Output: 5 Time Complexity: Space Complexity: Summary: The “Length of Last Word” problem can be solved using either an iterative approach from the end of the string or by trimming and splitting the string. Both approaches have a time complexity of O(n), but the iterative approach can be more space-efficient, using O(1) extra space.

Length of Last Word In C,CPP,JAVA,PYTHON,C#,JS Read More »

Group Anagrams In C,CPP,JAVA,PYTHON,C#,JS

The problem of Group Anagrams is a common algorithmic challenge that asks to group a list of strings such that each group consists of anagrams. Two words are considered anagrams if one can be formed by rearranging the letters of the other, i.e., they contain the same characters in the same frequency. Problem Statement: Given an array of strings, group the anagrams together. Input: Output: Example: Input: [“eat”, “tea”, “tan”, “ate”, “nat”, “bat”] Output: [[“eat”, “tea”, “ate”], [“tan”, “nat”], [“bat”]] Approach: The key observation for solving the Group Anagrams problem is that two strings are anagrams if and only if their sorted versions are identical. So, one approach is to sort each string and use the sorted version as a key to group the anagrams. Algorithm (in pseudocode): Complexity Analysis: Code Implementations: 1. C++ #include <iostream>#include <vector>#include <unordered_map>#include <algorithm>using namespace std;vector<vector<string>> groupAnagrams(vector<string>& strs) { unordered_map<string, vector<string>> anagramGroups; for (string s : strs) { string sorted_str = s; sort(sorted_str.begin(), sorted_str.end()); anagramGroups[sorted_str].push_back(s); } vector<vector<string>> result; for (auto& pair : anagramGroups) { result.push_back(pair.second); } return result;}int main() { vector<string> strs = {“eat”, “tea”, “tan”, “ate”, “nat”, “bat”}; vector<vector<string>> result = groupAnagrams(strs); for (auto& group : result) { for (string word : group) { cout << word << ” “; } cout << endl; } return 0;} 2. C #include <stdio.h>#include <string.h>#include <stdlib.h>#include <ctype.h>#define MAX_STR_LEN 100#define MAX_STRINGS 100// Function to compare two strings (used by qsort)int compareStrings(const void *a, const void *b) { return strcmp(*(const char **)a, *(const char **)b);}// Function to sort the characters of a stringvoid sortString(char *str) { int len = strlen(str); qsort(str, len, sizeof(char), compareStrings);}int main() { char *strs[] = {“eat”, “tea”, “tan”, “ate”, “nat”, “bat”}; int n = 6; // Temporary array to store sorted strings char *sortedStrs[n]; for (int i = 0; i < n; i++) { sortedStrs[i] = strdup(strs[i]); sortString(sortedStrs[i]); } // Grouping logic can be done manually (using hash maps, or just printing similar sorted strings) // This is just a simple illustration printf(“Grouped Anagrams:\n”); for (int i = 0; i < n; i++) { printf(“%s\n”, strs[i]); } return 0;} 3. Java import java.util.*;public class GroupAnagrams { public List<List<String>> groupAnagrams(String[] strs) { Map<String, List<String>> anagramGroups = new HashMap<>(); for (String s : strs) { char[] chars = s.toCharArray(); Arrays.sort(chars); String sortedStr = new String(chars); anagramGroups.putIfAbsent(sortedStr, new ArrayList<>()); anagramGroups.get(sortedStr).add(s); } return new ArrayList<>(anagramGroups.values()); } public static void main(String[] args) { GroupAnagrams solution = new GroupAnagrams(); String[] strs = {“eat”, “tea”, “tan”, “ate”, “nat”, “bat”}; List<List<String>> result = solution.groupAnagrams(strs); for (List<String> group : result) { System.out.println(group); } }} 4. Python from collections import defaultdictdef group_anagrams(strs): anagram_groups = defaultdict(list) for s in strs: sorted_str = ”.join(sorted(s)) anagram_groups[sorted_str].append(s) return list(anagram_groups.values())# Test the functionstrs = [“eat”, “tea”, “tan”, “ate”, “nat”, “bat”]result = group_anagrams(strs)for group in result: print(group) 5. C# using System;using System.Collections.Generic;public class GroupAnagrams { public List<List<string>> GroupAnagramsMethod(string[] strs) { var anagramGroups = new Dictionary<string, List<string>>(); foreach (string s in strs) { char[] chars = s.ToCharArray(); Array.Sort(chars); string sortedStr = new string(chars); if (!anagramGroups.ContainsKey(sortedStr)) { anagramGroups[sortedStr] = new List<string>(); } anagramGroups[sortedStr].Add(s); } var result = new List<List<string>>(); foreach (var group in anagramGroups.Values) { result.Add(group); } return result; } public static void Main() { GroupAnagrams solution = new GroupAnagrams(); string[] strs = {“eat”, “tea”, “tan”, “ate”, “nat”, “bat”}; var result = solution.GroupAnagramsMethod(strs); foreach (var group in result) { foreach (var word in group) { Console.Write(word + ” “); } Console.WriteLine(); } }} 6. JavaScript function groupAnagrams(strs) { const anagramGroups = {}; for (let str of strs) { const sortedStr = str.split(”).sort().join(”); if (!anagramGroups[sortedStr]) { anagramGroups[sortedStr] = []; } anagramGroups[sortedStr].push(str); } return Object.values(anagramGroups);}// Test the functionconst strs = [“eat”, “tea”, “tan”, “ate”, “nat”, “bat”];const result = groupAnagrams(strs);console.log(result); Summary: The Group Anagrams problem can be efficiently solved by using sorting or character counting and storing results in a hash map. The sorting method is the most straightforward and commonly used. The time complexity of the solution depends on the time to sort each string, which is O(klog⁡k)O(k \log k)O(klogk), where kkk is the average length of a string.

Group Anagrams In C,CPP,JAVA,PYTHON,C#,JS Read More »

Remove duplicates from Sorted Array

The objective is to rearrange a sorted array arr[] of size n so that every unique element appears at the beginning in sorted order. Return the length of this unique sorted subarray as well. Note: Since they have no bearing on the outcome, the items that follow the distinct ones can be in any sequence and have any value. Table of Content Hash Set Utilization: Effective for Unsorted Additionally, O(n) Space and O(n) Time C++ Java Python C# JavaScript Output 1 2 3 4 5

Remove duplicates from Sorted Array Read More »

Sort an array of 0s, 1s and 2s – Dutch National Flag Problem

Considering an array arr[] that only contains 0s, 1s, and 2s. Sorting the array means placing all 0s first, followed by all 1s and all 2s last. This issue is identical to the well-known “Dutch National Flag problem.” Edsger Dijkstra was the one who introduced the problem. The following is the issue: Given a line of n balls in a random arrangement, they can be red, white, or blue. All of the balls must be arranged so that they are adjacent to each other in the same color order, which is red, white, and blue (that is, all red balls should be placed first, followed by white balls, and finally blue balls). Table of Content [Naive Approach] Sorting – O(n * log(n)) Time and O(1) Space Sorting the array with a conventional sorting algorithm or sort library function is the naïve option. This will merely arrange all of the zeros first, followed by all of the ones and twos last. This method uses O(1) space and O(n * log(n)) time. [Better Approach] Counting 0s, 1s and 2s – Two Pass – O(n) Time and O(1) Space Counting the number of 0s, 1s, and 2s—let’s say c0, c1, and c2—after one traversal of the array is a superior method. Go through the array once again now, entering c0 (count of 0s) 0s first, followed by c1 1s and c2 2s. Although this method is unstable and necessitates two array traversals, it operates in O(n) time. C++ C Python C# JavaScript Output 0 0 1 1 2 2 Time Complexity: O(2 * n), where n is the number of elements in the arrayAuxiliary Space: O(1) The issues with this approach are:

Sort an array of 0s, 1s and 2s – Dutch National Flag Problem Read More »

Search in a row wise and column wise sorted matrix

Determine the location of X in the matrix, if it exists, given a N X N matrix and an integer X. Print “Element not found” otherwise. The matrix’s rows and columns are arranged in ascending order. Approaches to Search in row wise and column wise sorted matrix: [Naive Approach] Traversing the Complete Matrix – O(N^2) Time and O(1) Space Expected Approach] Removing row or column in each comparison – O(N) Time and O(1) Space [Naive Approach] Traversing the Complete Matrix – O(N^2) Time and O(1) Space: C++ C Java Python JS Output Element found at (2, 1) Time Complexity: O(N2)Auxiliary Space: O(1), since no extra space has been taken

Search in a row wise and column wise sorted matrix Read More »

Text Justification- DSA Solution

Format the text so that each line has precisely W characters, left and right justified, given an array of strings arr[] and a width W. Put as many words as you can in each line, try to divide the additional spaces evenly, and if they don’t divide evenly, put more spaces to the left. There should be no extra spaces between words in the final line, which should be left-justified. For instance: Method: The initial step is to decide which words, with one space between each pair of words, can be put into each line. Each line must be justified after the words have been chosen. The total length of the words that are contained, separated by one space, must be less than or equal to W in order for a line to be justified. Additionally, if the current line is the text’s last line, we must add spaces to it so that its width equals W. If not, count the number of spaces required to make each line W long and evenly distribute them if the current line is not the last line. C++ Java Python C# JS Output Sky is the bestcomputer scienceportal forWebz. Time Complexity: O(N), where N is the sum of length of all words.Auxiliary Space: O(W), where W is the max width of a line.

Text Justification- DSA Solution Read More »