×

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

Python Dictionary

Dictionary in Python is an unordered collection of data values, which is used to store data values like a map. Unlike different data types that hold just individual assets as...

4 minutes read.

Python Static Method

Introduction to methods that are majorly used in Python: Class MethodsInstance MethodsStatic Methods Before going to the in-depth concept of Static Methods, let us briefly discuss Class Methods and Instance Methods. Class Methods The...

4 minutes read.

Arithmetic Expressions in Python

What is Python Expression? Expressions are collections of operands and operators. Python expressions are translated by the Python interpreter into some value or outcome. In Python, an expression is made up...

13 minutes read.

Python data science course

What is meant by Data Science? When processing raw, structured, and unstructured data utilizing various technologies, algorithms, and the scientific method, data science is a detailed study of the enormous quantity...

4 minutes read.

Python 2.7 data structures

The rundown information type has a few additional techniques. Here is every one of the strategies for listing objects: list.append(x): Add a thing to the furthest limit of the rundown; comparable...

9 minutes read.

Python String split() method

The string.split() method in Python splits a string into a list and returns a list of the words in the string. If the parameter maxsplit is given, at most maxsplit splits are done. If maxsplit is...

2 minutes read.

Python Project Ideas for Beginners

Python project ideas for beginners Advanced Python is an amazing platform to grow and achieve success as a developer in the future. Python is a programming language that can be very...

7 minutes read.

Python complex() class

Python complex() class The complex() class in Python returns a complex number or converts a string or number to a complex number. Syntax class complex([real[, imag]]) Parameter Real: This parameter consists of a number representing the real...

1 minute read.

Installing Packages in Python

It's critical to understand that the term "package" here refers to a collection of software that must be installed (i.e. as a synonym for a distribution). It has nothing to...

6 minutes read.

Python List

The list is one of the most versatile, mutable data-structures in Python. It can store heterogeneous data or different types of data. The list contains comma-separated values (item) within the square brackets. Creating...

4 minutes read.

Decision Tree in Python

Decision Tree is one of the most essential algorithms in the area of machine learning for classification and regression. But let us first talk about the lifespan of every machine learning...

12 minutes read.

Find Last Occurrence of Substring using Python

Introduction When planning to work with strings, we may need to determine whether a substring is present. This issue is rather typical, and there have been numerous discussions about how to...

3 minutes read.

Return Statement In Python

Python Return Statement The return statement is generally used for the execution ending and returns the value back to the caller. The return statement can return all types of values and...

2 minutes read.

Python Parser

Introduction : Parsing is referred to as the processing and translation of a Python program into machine language. In general, we could indeed say that the command parse is used to...

4 minutes read.

Python Data Types

Python Data Types: The variable in Python is used to store values, and they can hold different values. Each variable in Python has its own data-type. Since Python is a...

13 minutes read.

Python MySQL

In this article, we are going to learn the following: How to connect Python to MySQL.How to create a new Database.Procedure for connecting the newly created database.Procedure for connecting the already...

7 minutes read.

Python try catch exception

The try-except proclamation can deal with exceptions. Exceptions might happen when you run a program. Exceptions are blunders that occur during the execution of the program. Python won't educate you regarding...

3 minutes read.

How to set up a proxy using selenium in python

What is Proxy? A proxy acts as a middleman between user requests and server responses. The main purposes of proxies are to protect user privacy and encapsulate data between various interactive...

3 minutes read.

Python Dictionary Methods

Python Dictionary Methods Python has a set of built-in methods that dictionary objects can call. All the python dictionary methods are as follow: Methods Description clear() The dictionary.clear() method removes all the elements...

3 minutes read.

Python List append() Method

Python List append() Method The list.append() method in Python adds or appends an item to the end of the list. Syntax list.append(x) Parameter x: It is a required parameter that represents an element of any type (string, number,...

1 minute read.