×

First Unique Character in a String Python

This article aims to introduce you to strings and how to create a string in Python, and then we will solve a simple yet exciting DSA (Data Structures and Algorithms) problem which is frequently asked in Product based companies like Amazon, Microsoft, Adobe and Google like Maang and other very good product-based Start-up companies which are to find the first unique character in a String and to return its index.

To summarise, Strings in Python Programming language are a series or group of characters which are immutable in nature. We will be using either single or double quotes to declare a string under a variable in any Programming language. We can use the backslash character to escape the usage of quotes power on the String we have declared. We will use the len() function to find the length of the String, and in the same way, we will be using str[n], which is the string name inside the square brackets passing on the integer value of the character that we would like to access.

What are Strings in Python

A String is nothing but a group of characters which can either be words or sentences or even code sometimes. Strings in Python are created using a suitable variable type to the type of data attached to it, and the value of the String that we have written will be declared under single quotes or can be in double quotes.

Creating Strings in Python

Code

Creating_a_String_Variable = “Write your String input value under the double quotes here”
My_String = “javaTpoint.com”
print(My_String)
capital_of_India = “New Delhi”
print(capital_of_India)

Output

javaTpoint.com
New Delhi

Finding the First Unique Character in a String Python

Problem Statement: We are given a String input, and the task is to find the unique character in the String and return the index of the character where it exists. Or, to explain more clearly, we need to find the first non-repeating character in the given String, which is assigned as an input and return the index of the character position in the String. In any test cases that we are provided with, if there is no unique character, then we have to return -1 as an output simply.

Python code

class Solution:
    def firstUniqChar(self, s: str) -> int:
        
        
        #Here, we are trying to leverage the usage of hash maps to store the first element if it occurs
        first_unique={}
        #Again, here we are using the hashmaps to keep a check on the all characters that we have        #visited
        string_elem={}
        #As a key and value pairs, we will again use a hash mapping to it
#We will here try to iterate over all the characters to check.
        for i in range(len(s)):
            #below conditioning code will check if the character is visited or not
            if s[i] not in string_elem:
                #if the condition states that it is not visuited then we will add up to the hashmap
                first_unique[s[i]] = i
                string_elem[s[i]] = i
            #below code will check if the element is unique or if it is repeated character
            elif s[i] in first_unique:
                #if present then remove it
                first_unique.pop(s[i])
                
        #below conditioning code will return the position of the character or the index to say if the #element is unique amongst the characters in the string we are given with
        if(len(first_unique)>0):
            res = list(first_unique.keys())[0]
            return first_unique[res]#otherwise return -1
        else:
            return -1

Output:

Possible input and output variant- 1

Input: s = “javatpoint”
Output: 0

Possible input and output variant- 2

Input: s = “NiceNice”
Output:   -1

Possible C++ code for the same problem

C++ code

class Solution {
public:
    int firstUniqChar(string s) {
        int freq[26] = {0};
        int ans = -1;
        for(int i = 0; i<s.size() ; i++){
            freq[s[i]-'a']++;
        }
        
        for(int i = 0; i<s.size(); i++){
            if(freq[s[i]-'a'] == 1){
                ans = i;
                break;
            }
        }
        return ans;
    }
};

Output:

Possible input and output variant- 1

Input: s = “Ababbaacferty”
Output: 7

Possible JavaScript code for the same problem

Code

const firstUniqChar = (s) => {
let hashTable = {};
for (let i = 0; i <= s.length - 1; i++) {
if (hashTable.hasOwnProperty(s[i])) {
hashTable[s[i]] = 2;
} else {
hashTable[s[i]] = 1;
}
}
for (let i = 0; i <= s.length - 1; i++) {
if (hashTable.hasOwnProperty(s[i]) && hashTable[s[i]] === 1) {
return i;
}
}
return -1;
};

Output:

Possible input and output variant- 1

Input: s = “ aabbaa”
Output: -1

Related Topics

How to Install Tweepy in Python

In this article, we will learn or understand how to install Tweepy in Python and what Tweepy is. Firstly, let’s understand What Tweepy is. As we all know, one of the...

3 minutes read.

Python while loop

Loops are essential in Python or any other programming language, as they help to execute a block of code repetitively. Sometimes, situations arise where you would need to use a piece of code...

2 minutes read.

Add Dictionary to Dictionary in Python

Dictionary in python: Python's execution of a data model, known more commonly as an implicit array, is a dictionary. A dictionary is made up of a group of key-value pairs. Each...

4 minutes read.

Python List pop() method

Python List pop() method The list.pop() method removes the item at the specified position in the list, and return it. If no index is specified, this method removes and returns the last item in the list. Syntax list.pop([i]) Parameter i:...

1 minute read.

Sort Dictionary in Python

Dictionaries In Python, a dictionary is an unordered collection or set of data types that enable of store data in an unordered key-value/pair. The key is stored alongside with value. Dictionary contains key:...

4 minutes read.

Python type() Function

Python type() Function The type() function in Python returns the type of an object. The return value is a type object and generally the same object as returned by object.__class__. Syntax class type(object)      ...

1 minute read.

Python Lexicographic Order

Python lexicographic order Before we discuss the lexicographic order in Python, we should understandwhat is lexicographic order and sort according to lexicographic order. Lexicographic order In mathematics, the generalization of the alphabetical order...

5 minutes read.

Insertion Sort using Python

Insertion sort is a type of sorting technique that is used for sorting an array with random elements. Using sorting methods, any unsorted array can be sorted into ascending or...

3 minutes read.

Python Combination

Python Combination Permutations and combinations are the important part of our mathematical tools. We use them often in our Python programs. In this tutorial, we will learn about combinations in Python...

6 minutes read.

Python Fit Transform

In machine learning, fit (), transform(), fit transform () methods are provided by scikit learn package. This package is used in model fitting and data processing. These methods are implemented...

2 minutes read.

Python Command line Arguments

Python Command line Arguments The command-line argument is used to the change functionality of the program. It's an extra command the programmer can use while launching a program. These commands have many uses...

7 minutes read.

How to Call a Function in Python

How To Call a Function in Python Functions are the well-defined and structured piece of code that is used to implement specific functionality. Calling a function in python is the best...

4 minutes read.

How to build a Virtual Assistant Using Python

What is a virtual assistant? A virtual assistant is a new and very interesting concept in today’s world. When we hear the word “Virtual Assistant”, we can easily visualize “Jarvis or...

8 minutes read.

Anonymous/Lambda Function in Python

Lambda keyword is used to declare an Anonymous function, i.e. a function that does not have any name. It is also called Anonymous functions. In python, normal functions are defined...

3 minutes read.

Python Program to Convert Decimal into Binary, Octal, and Hexadecimal

Python Program to Convert Decimal into Binary, Octal, and Hexadecimal We know that the most widely used number system is a decimal system, but the computer only understands binary values. The...

2 minutes read.

Python SymPy

A Python package for symbolic mathematics is called SymPy. Its goal is to develop into a fully-fledged computer algebra system (CAS) while maintaining the code as straightforward as possible to...

3 minutes read.

How To Install Python In Ubuntu

How To Install Python In Ubuntu Ubuntu is free and open-source software and it is an essential part of the Linux distribution. It is a popular operating system developed by Canonical. If we...

3 minutes read.

Python Set update() method

Python Set update() method The set.update() method in Python updates the current set, by adding items from another set. If an element is common in both the sets, only one appearance of this item...

1 minute read.

Count Number of Keys in Dictionary Python

Dictionary is a particular data type in python. Dictionary stores unique values by taking different keys and their assigned values. Through this article, we will learn about python dictionary count,...

3 minutes read.

What is Python 2

Python is a widely used high-level language. The initial work on developing python was begun in the late 1980s. In 1989, Guido Van Rossum started to work on it. Initially,...

3 minutes read.