Mikel  Okuneva

Mikel Okuneva

1597978800

Find value after N operations to remove N characters of string S with given constraints

Given a string** S** of Size N. Initially, the value of count is 0. The task is to find the value of count after N operations to remove all the N characters of the given string S where each operation is:

  • In each operation, select an alphabetically the smallest character in the string S and remove that character from S and add its index to count.
  • If multiple characters are present then remove the character having the smallest index.

Note: Consider string as 1-based indexing.

Examples:

Input:_ N = 5, S = “abcab” _

Output:_ 8 _

Explanation:

_Remove character ‘a’ then string becomes “bcab” and the count = 1. _

_Remove character ‘a’ then string becomes “bcb” and the count = 1 + 3 = 4. _

_Remove character ‘b’ then string becomes “cb” and the count = 4 + 1 = 5. _

_Remove character ‘b’ then string becomes “c” and the count = 5 + 2 = 7. _

Remove character ‘c’ then string becomes “” and the count = 7 + 1 = 8.

Input:_ N = 5 S = “aabbc” _

Output:_ 5 _

Explanation:

The value after 5 operations to remove all the 5 characters of String aabbc is 5.

Recommended: Please try your approach on {IDE} first, before moving on to the solution.

**Naive Approach: **The idea is to check if the string is empty or not. If it is not empty then following are the steps to solve the problem:

  • Find the first occurrence of the smallest alphabets in the current string, let’s say ind and remove it from the string.
  • Increase the count by **ind **+ 1.
  • Repeat the above step until the string becomes empty.

Below is the implementation of the above approach:

  • C++
  • Java
  • C#

// C++ program for the above approach

#include <iostream>

#include <string>

**using** **namespace** std;

// Function to find the value after

// N operations to remove all the N

// characters of string S

**void** charactersCount(string str, **int** n)

{

**int** count = 0;

// Iterate till N

**while** (n > 0) {

**char** cur = str[0];

**int** ind = 0;

**for** (``**int** j = 1; j < n; j++) {

**if** (str[j] < cur) {

cur = str[j];

ind = j;

}

}

// Remove character at ind and

// decrease n(size of string)

str.erase(str.begin() + ind);

n--;

// Increase count by ind+1

count += ind + 1;

}

cout << count << endl;

}

// Driver Code

**int** main()

{

// Given string str

string str = "aabbc"``;

**int** n = 5;

// Function call

charactersCount(str, n);

**return** 0;

}

Output:

5

Time Complexity:_ O(N2)_

Auxiliary Space:_ O(1)_

**Efficient Approach: **This problem can be solved using the concept of Binary Index Tree or Fenwick Tree. Below are the steps:

  • Initially, Store the values of indices of all the characters/alphabet in increasing order.
  • Start with the smallest alphabet ‘a’ and remove all ‘a’s in the order of there occurrence. After removing, select the next alphabet ‘b’, and repeat this step until all alphabets are removed.
  • Removing the character means that its corresponding value in the array is changed to 0, indicating that it is removed.
  • Before removing, find the position of the character in the string using the sum() method in Fenwick Tree and add the position value to the count.
  • After removing all the characters in the string, the value of count is obtained.

#advanced data structure #divide and conquer #strings #tree #segment-tree #trees

What is GEEK

Buddha Community

Find value after N operations to remove N characters of string S with given constraints
Mikel  Okuneva

Mikel Okuneva

1597978800

Find value after N operations to remove N characters of string S with given constraints

Given a string** S** of Size N. Initially, the value of count is 0. The task is to find the value of count after N operations to remove all the N characters of the given string S where each operation is:

  • In each operation, select an alphabetically the smallest character in the string S and remove that character from S and add its index to count.
  • If multiple characters are present then remove the character having the smallest index.

Note: Consider string as 1-based indexing.

Examples:

Input:_ N = 5, S = “abcab” _

Output:_ 8 _

Explanation:

_Remove character ‘a’ then string becomes “bcab” and the count = 1. _

_Remove character ‘a’ then string becomes “bcb” and the count = 1 + 3 = 4. _

_Remove character ‘b’ then string becomes “cb” and the count = 4 + 1 = 5. _

_Remove character ‘b’ then string becomes “c” and the count = 5 + 2 = 7. _

Remove character ‘c’ then string becomes “” and the count = 7 + 1 = 8.

Input:_ N = 5 S = “aabbc” _

Output:_ 5 _

Explanation:

The value after 5 operations to remove all the 5 characters of String aabbc is 5.

Recommended: Please try your approach on {IDE} first, before moving on to the solution.

**Naive Approach: **The idea is to check if the string is empty or not. If it is not empty then following are the steps to solve the problem:

  • Find the first occurrence of the smallest alphabets in the current string, let’s say ind and remove it from the string.
  • Increase the count by **ind **+ 1.
  • Repeat the above step until the string becomes empty.

Below is the implementation of the above approach:

  • C++
  • Java
  • C#

// C++ program for the above approach

#include <iostream>

#include <string>

**using** **namespace** std;

// Function to find the value after

// N operations to remove all the N

// characters of string S

**void** charactersCount(string str, **int** n)

{

**int** count = 0;

// Iterate till N

**while** (n > 0) {

**char** cur = str[0];

**int** ind = 0;

**for** (``**int** j = 1; j < n; j++) {

**if** (str[j] < cur) {

cur = str[j];

ind = j;

}

}

// Remove character at ind and

// decrease n(size of string)

str.erase(str.begin() + ind);

n--;

// Increase count by ind+1

count += ind + 1;

}

cout << count << endl;

}

// Driver Code

**int** main()

{

// Given string str

string str = "aabbc"``;

**int** n = 5;

// Function call

charactersCount(str, n);

**return** 0;

}

Output:

5

Time Complexity:_ O(N2)_

Auxiliary Space:_ O(1)_

**Efficient Approach: **This problem can be solved using the concept of Binary Index Tree or Fenwick Tree. Below are the steps:

  • Initially, Store the values of indices of all the characters/alphabet in increasing order.
  • Start with the smallest alphabet ‘a’ and remove all ‘a’s in the order of there occurrence. After removing, select the next alphabet ‘b’, and repeat this step until all alphabets are removed.
  • Removing the character means that its corresponding value in the array is changed to 0, indicating that it is removed.
  • Before removing, find the position of the character in the string using the sum() method in Fenwick Tree and add the position value to the count.
  • After removing all the characters in the string, the value of count is obtained.

#advanced data structure #divide and conquer #strings #tree #segment-tree #trees

Ray  Patel

Ray Patel

1619565060

Ternary operator in Python?

  1. Ternary Operator in Python

What is a ternary operator: The ternary operator is a conditional expression that means this is a comparison operator and results come on a true or false condition and it is the shortest way to writing an if-else statement. It is a condition in a single line replacing the multiline if-else code.

syntax : condition ? value_if_true : value_if_false

condition: A boolean expression evaluates true or false

value_if_true: a value to be assigned if the expression is evaluated to true.

value_if_false: A value to be assigned if the expression is evaluated to false.

How to use ternary operator in python here are some examples of Python ternary operator if-else.

Brief description of examples we have to take two variables a and b. The value of a is 10 and b is 20. find the minimum number using a ternary operator with one line of code. ( **min = a if a < b else b ) **. if a less than b then print a otherwise print b and second examples are the same as first and the third example is check number is even or odd.

#python #python ternary operator #ternary operator #ternary operator in if-else #ternary operator in python #ternary operator with dict #ternary operator with lambda

HI Python

HI Python

1621610100

Python program to remove last N characters from a string

Given a string S and an integer N, the task is to remove N characters from the end of the string S.

Input:_ S = “GeeksForGeeks”, N = 5_

_Output: _GeeksFor

_Explanation: _Removing the last 5 characters from “GeeksForGeeks” modifies the string to “GeeksFor”.

_Input: _S = “Welcome”, N = 3

_Output: _Welc

**Approach 1: **Follow the steps below to solve the problem:

#python programs #strings #python-string-functions

Rust  Language

Rust Language

1640144506

Strings - The Rust Programming Language

Rust For Beginners Tutorial - Strings

In this video we're taking a look at the String, &String and &str types in Rust!

Exercise solutions: https://github.com/PascalPrecht/rustlings/commits/solutions 

---
0:00 Intro
0:09 Exercise 1
4:47 Exercise 2
10:38 Outro


Strings

There are two types of strings in Rust: String and &str.

A String is stored as a vector of bytes (Vec<u8>), but guaranteed to always be a valid UTF-8 sequence. String is heap allocated, growable and not null terminated.

&str is a slice (&[u8]) that always points to a valid UTF-8 sequence, and can be used to view into a String, just like &[T] is a view into Vec<T>.

fn main() {
    // (all the type annotations are superfluous)
    // A reference to a string allocated in read only memory
    let pangram: &'static str = "the quick brown fox jumps over the lazy dog";
    println!("Pangram: {}", pangram);

    // Iterate over words in reverse, no new string is allocated
    println!("Words in reverse");
    for word in pangram.split_whitespace().rev() {
        println!("> {}", word);
    }

    // Copy chars into a vector, sort and remove duplicates
    let mut chars: Vec<char> = pangram.chars().collect();
    chars.sort();
    chars.dedup();

    // Create an empty and growable `String`
    let mut string = String::new();
    for c in chars {
        // Insert a char at the end of string
        string.push(c);
        // Insert a string at the end of string
        string.push_str(", ");
    }

    // The trimmed string is a slice to the original string, hence no new
    // allocation is performed
    let chars_to_trim: &[char] = &[' ', ','];
    let trimmed_str: &str = string.trim_matches(chars_to_trim);
    println!("Used characters: {}", trimmed_str);

    // Heap allocate a string
    let alice = String::from("I like dogs");
    // Allocate new memory and store the modified string there
    let bob: String = alice.replace("dog", "cat");

    println!("Alice says: {}", alice);
    println!("Bob says: {}", bob);
}

More str/String methods can be found under the std::str and std::string modules

Literals and escapes

There are multiple ways to write string literals with special characters in them. All result in a similar &str so it's best to use the form that is the most convenient to write. Similarly there are multiple ways to write byte string literals, which all result in &[u8; N].

Generally special characters are escaped with a backslash character: \. This way you can add any character to your string, even unprintable ones and ones that you don't know how to type. If you want a literal backslash, escape it with another one: \\

String or character literal delimiters occuring within a literal must be escaped: "\"", '\''.

fn main() {
    // You can use escapes to write bytes by their hexadecimal values...
    let byte_escape = "I'm writing \x52\x75\x73\x74!";
    println!("What are you doing\x3F (\\x3F means ?) {}", byte_escape);

    // ...or Unicode code points.
    let unicode_codepoint = "\u{211D}";
    let character_name = "\"DOUBLE-STRUCK CAPITAL R\"";

    println!("Unicode character {} (U+211D) is called {}",
                unicode_codepoint, character_name );


    let long_string = "String literals
                        can span multiple lines.
                        The linebreak and indentation here ->\
                        <- can be escaped too!";
    println!("{}", long_string);
}

Sometimes there are just too many characters that need to be escaped or it's just much more convenient to write a string out as-is. This is where raw string literals come into play.

fn main() {
    let raw_str = r"Escapes don't work here: \x3F \u{211D}";
    println!("{}", raw_str);

    // If you need quotes in a raw string, add a pair of #s
    let quotes = r#"And then I said: "There is no escape!""#;
    println!("{}", quotes);

    // If you need "# in your string, just use more #s in the delimiter.
    // There is no limit for the number of #s you can use.
    let longer_delimiter = r###"A string with "# in it. And even "##!"###;
    println!("{}", longer_delimiter);
}

Want a string that's not UTF-8? (Remember, str and String must be valid UTF-8). Or maybe you want an array of bytes that's mostly text? Byte strings to the rescue!

use std::str;

fn main() {
    // Note that this is not actually a `&str`
    let bytestring: &[u8; 21] = b"this is a byte string";

    // Byte arrays don't have the `Display` trait, so printing them is a bit limited
    println!("A byte string: {:?}", bytestring);

    // Byte strings can have byte escapes...
    let escaped = b"\x52\x75\x73\x74 as bytes";
    // ...but no unicode escapes
    // let escaped = b"\u{211D} is not allowed";
    println!("Some escaped bytes: {:?}", escaped);


    // Raw byte strings work just like raw strings
    let raw_bytestring = br"\u{211D} is not escaped here";
    println!("{:?}", raw_bytestring);

    // Converting a byte array to `str` can fail
    if let Ok(my_str) = str::from_utf8(raw_bytestring) {
        println!("And the same as text: '{}'", my_str);
    }

    let _quotes = br#"You can also use "fancier" formatting, \
                    like with normal raw strings"#;

    // Byte strings don't have to be UTF-8
    let shift_jis = b"\x82\xe6\x82\xa8\x82\xb1\x82\xbb"; // "ようこそ" in SHIFT-JIS

    // But then they can't always be converted to `str`
    match str::from_utf8(shift_jis) {
        Ok(my_str) => println!("Conversion successful: '{}'", my_str),
        Err(e) => println!("Conversion failed: {:?}", e),
    };
}

For conversions between character encodings check out the encoding crate.

A more detailed listing of the ways to write string literals and escape characters is given in the 'Tokens' chapter of the Rust Reference.

#rust #programming #developer 

What is difference between String and string in C#

Are you confused about System.String and string in C#? What is the difference between String and string in C#? And how to choose between string and System.String? In this article, I am going to show you all the differences between string and System.String in C## with code examples. .

What is the difference between System.String and string in C#?

Basically, there is no difference between string and String in C#. “string” is just an alias of System.String and both are compiled in the same manner. String stands for System.String and it is a .NET Framework type. “string” is an alias in the C## language for System.String. Both of them are compiled to System.String in IL (Intermediate Language), so there is no difference.

#c# #string #string and string