Commonly Asked Cognizant Interview Questions for the 2023 Recruitment - IQCode

About Cognizant

Cognizant is a technology company based in the United States that provides business consulting, information technology, and outsourcing services. The company is headquartered in Teaneck, New Jersey. It is a member of NASDAQ-100, S&P 500, Forbes Global 2000, and Fortune 500, and is one of the fastest-growing and most successful organizations in the world.

Cognizant helps businesses in modernizing technology, reimagining processes, and enhancing customer experiences to stay ahead in an ever-changing environment. It specializes in information technology, information security, consulting, ITO, and BPO services. Cognizant's business is divided into three areas: digital business, digital operations, and digital systems and technology.

Cognizant provides a great learning opportunity and allows aspiring software engineers to create a career path. It is one of the leading MNCs offering Fresher Jobs in India. Working here exposes individuals to new technologies and provides the opportunity to work with global customers, which helps in improving their talents, problem-solving ability, and entrepreneurial spirit.

Eligibility Criteria:

  • The applicant must have more than 60% marks in 10th and 12th (or diploma).
  • The applicant must have a minimum of 60% marks in graduation.
  • A maximum interval of one year is permitted after HSC(12th), but not after SSC(10th), or between semesters of graduation.
  • Graduation and post-graduation in BE, B Tech, ME, M Tech, MCA
  • At the time of the Cognizant selection process, a candidate should not have any pending backlogs.

Cognizant Recruitment Process

The interview process consists of multiple rounds to ensure that the best candidates are selected for the job.

Cognizant Technical Interview Questions: Freshers and Experienced

One of the commonly asked interview questions is to write code to find the length of a string without using string functions. Here's an example:


  int findLengthOfString(char str[]) {
    int count = 0; // initialize count variable
    while (str[count] != '\0'){ // loop through each character until null character is found
      count++; // increment count variable for each character
    }
    return count; // return count variable
  }

In the above example, the function

findLengthOfString

takes a character array as an input parameter

str

and outputs an integer value that represents the length of the string.

By using a while loop, we can iterate through each character until we encounter the null character. For each character in the string, we increment the count variable until we reach the end of the string. Finally, we return the count variable, which represents the length of the string.

Printing the Address of a Variable Without a Pointer

To print the address of a variable without using a pointer in C++, you can use the address-of operator (&) followed by the variable name. This operator returns the memory address of the variable in hexadecimal format.

Here's an example:


#include <iostream>
using namespace std;

int main() {
  int num = 10;
  cout << "The address of the variable 'num' is: " << &num << endl;
  return 0;
}

Output:


The address of the variable 'num' is: 0x7ffcb629570c

In the above code, we declared an integer variable 'num' and assigned it a value of 10. Then we printed the memory address of the 'num' variable using the address-of operator followed by the variable name '&num'. Note that the memory address may differ each time you run the program because of memory allocation by the operating system.

By using this method, we can print the memory address of a variable without using a pointer in C++.

Understanding Proactive, Retroactive, and Simultaneous Update in DBMS

In the context of Database Management Systems (DBMS), proactive updates refer to a technique where updates on one transaction do not affect other transactions until the changes have been committed. This means that other transactions executing concurrently will not see the updated data until the transaction has been committed.

On the other hand, retroactive updates refer to a technique where the updates are visible to other transactions before the changes have been committed. This means that other transactions executing concurrently will see the updated data even if the transaction that made the changes is rolled back.

Simultaneous update refers to a technique where multiple transactions can update the same data at the same time without causing conflicts or problems with data consistency. The DBMS will handle the conflicts and ensure the integrity of data during simultaneous updates.

Understanding these different techniques for updating data in DBMS is important for designing efficient and reliable database systems.

Differences between Generalization and Specialization in DBMS

In a database management system (DBMS), generalization and specialization are two concepts that are used for organizing and representing data.

1. Definition: Generalization is a process of extracting common properties from a set of entities and creating a generalized entity from them. Specialization is a process of identifying subsets of an entity that share common attributes or relationships to form a new sub-entity.

2. Direction: Generalization moves from specific entities to a generalized entity. Specialization moves from a generalized entity to more specific sub-entities.

3. Relationship: Generalization is a "is-a" relationship that involves creating a higher-level, more generalized entity that encompasses lower-level, more specific entities. Specialization is a "part-of" relationship that involves splitting an entity into smaller sub-entities.

4. Usage: Generalization is used when there are commonalities between entities that can be grouped together as a single entity. Specialization is used to represent a subset of an entity that has unique attributes or characteristics.

5. Example: Generalization can be used to create a superclass "Vehicle" that includes all types of vehicles such as cars, buses, and trucks. Specialization can be used to create subclasses of "Vehicle" such as "Sports Car" or "Truck with Trailer".

Overall, both generalization and specialization can help in optimizing the database design and enhancing its performance.

What is the Fill Factor in SQL and what is its default value?

In SQL, the fill factor is the percentage of space on each leaf-level page to be filled with data. The remaining free space on each page is reserved for future growth. The fill factor value can range from 1 to 100.

By default, the fill factor value is 0, which means that the database engine determines the fill factor value based on the table's size and other factors. This can lead to fragmentation and decreased performance. Therefore, it is recommended to set an appropriate fill factor value for tables and indexes based on their expected growth and usage pattern.

Index Hunting: Its Purpose and Benefits for Query Performance

Index hunting refers to the process of identifying and optimizing database indexes to improve the speed and efficiency of database queries. Indexing involves creating data structures that provide quick access to data rows in a database table based on specific column values. Essentially, indexing helps reduce the need for the database engine to scan every row of a table to locate the data needed by a query.

By strategically adding indexes to database tables, developers can significantly improve query performance, as queries can be executed more quickly and with fewer resources. However, too many indexes can also negatively impact performance, as updates and inserts on a table require updates to the indexes. Therefore, it's essential to find the right balance between having enough indexes to optimize queries and keeping the number of indexes to a minimum to avoid performance issues caused by excessive indexing.

Overall, index hunting is a critical step in database optimization, and it can significantly improve the speed and efficiency of database queries, leading to a better application performance and user experience.

Steps to Create, Update, and Drop a View in SQL

Creating a View:

1. Begin by logging in to the SQL Server Management Studio. 2. Open a new query window and select the appropriate database. 3. Type the following CREATE VIEW statement:


CREATE VIEW view_name AS
SELECT column1, column2, column3
FROM table_name
WHERE condition;

4. Replace view_name with the desired name of the view that you want to create. 5. Replace column1, column2, column3 with the names of the columns that you want included in the view. 6. Replace table_name with the name of the table that you want to use in the view. 7. Replace the WHERE condition with the condition that will be used to filter the data.

Updating a View:

1. Open SQL Server Management Studio and open a query window that is connected to the appropriate database. 2. Type the following ALTER VIEW statement:


ALTER VIEW view_name AS
SELECT column1, column2, column3
FROM table_name
WHERE new_condition;

3. Replace view_name with the name of the view that you want to update. 4. Replace column1, column2, column3 with the names of the columns included in the view that you want to update. 5. Replace table_name with the name of the table that you want to use in the view. 6. Replace new_condition with the updated condition that will be used to filter the data.

Dropping a View:

1. Open SQL Server Management Studio and connect to the appropriate database. 2. Open a new query window and type the following DROP VIEW statement:


DROP VIEW view_name;

3. Replace view_name with the name of the view that you want to drop. 4. Press F5 or click the Execute button to run the query and drop the view.

Comparison of Shortest Job First (SJF) and Shortest Remaining Time First (SRTF) CPU Scheduling Algorithms

The SJF and SRTF are both CPU scheduling algorithms that prioritize jobs with the lowest burst time. They are designed to minimize the average waiting time of processes in the ready queue.

The main difference between the two algorithms is that SJF is a non-preemptive algorithm, meaning that once a process is assigned the CPU, it will run until it is completed. On the other hand, SRTF is a preemptive algorithm, which means that it gives priority to a process with shorter burst time, and if a new process with even shorter burst time arrives, it preempts the currently running process and assigns the newly arrived process to the CPU. Thus, SRTF results in even lower average waiting time compared to SJF.

Another difference is that SJF requires knowledge of the burst times of all the processes in the ready queue, while SRTF only requires knowledge of the remaining burst time of the currently running process and the burst times of the processes in the ready queue.

Both algorithms have advantages and disadvantages, and the choice between them depends on the context in which they are used. In general, SRTF is more efficient in minimizing waiting time, but it requires more overhead and may lead to starvation of some processes with longer burst times. SJF, on the other hand, is simpler and fairer to all processes, but it may not always result in optimal performance.


Factors Affecting the Need for a Detection Algorithm in a Deadlock Avoidance System

In a deadlock avoidance system, there are several factors that determine whether or not a detection algorithm is needed. These factors include:

1. The size and complexity of the system: For larger and more complex systems, it may be necessary to use a detection algorithm to identify potential deadlocks.

2. The criticality of the system: If the system is critical and cannot afford any downtime, a detection algorithm may be necessary to avoid potential deadlocks.

3. The frequency of deadlock occurrences: If deadlocks occur frequently, it may be necessary to use a detection algorithm to identify the root cause and prevent future deadlocks.

4. The cost of implementing a detection algorithm: If the cost of implementing a detection algorithm is low, it may be worth the investment to ensure system reliability.

Overall, the decision to use a detection algorithm in a deadlock avoidance system depends on the specific requirements and constraints of the system.

How Dynamic Loading Improves Memory Space Utilization?

Dynamic loading is a technique used in computing to load libraries or modules into memory only when they are needed. This process can help to improve memory utilization and conserve resources.

By loading only the required modules or libraries at the time when they are actually needed, dynamic loading minimizes the amount of memory space wasted on loading and storing unnecessary modules. This technique allows programs to start up and execute more quickly, reducing the overall memory footprint of the system.

Dynamic loading also allows for greater flexibility in program design since modules can be loaded or unloaded as needed during runtime, rather than having to be defined at compile time.

In summary, dynamic loading can be a useful technique for optimizing memory usage in computing systems. It can help programs to load more quickly, reduce memory waste, and increase flexibility in program design.

What is the Root Partition in an Operating System?

The root partition is the top-level directory of a file system in an operating system. It contains all of the other directories and files in the file system. In Unix-based systems, the root partition is identified by the "/" symbol. It is essential for the proper functioning of the operating system, as it contains crucial system files and libraries. Without the root partition, the operating system would not be able to boot up or operate correctly.

The Purpose of a Virtual File System (VFS)

A Virtual File System (VFS) is a software layer in an operating system between the file system implementation and the user-facing applications, providing a uniform interface to different types of file systems. The main purpose of a VFS is to allow multiple file systems to be supported on a single operating system, making it easier for the user to access and manage different types of files and storage devices through a common interface. Additionally, a VFS provides a level of abstraction and security by allowing the system to enforce permissions and access controls for all file system operations.

What is Caching and How Does it Work?

Caching is the process of storing frequently used data temporarily in a cache, which is a memory or storage area, for faster access in the future. The cache can be located on the client-side (such as in a web browser) or on the server-side.

In web development, caching is often used to improve website performance. When a website is loaded, resources such as images, stylesheets, and scripts are downloaded from the server to the client-side cache. The next time the website is loaded, if the resources have not changed, the browser can retrieve them from the cache instead of making a new request to the server. This results in faster load times and reduced server load.

Caching works by using a key-value pair system, where the key is the resource being requested and the value is the resource data stored in the cache. When a user requests a resource, the caching system first checks if the resource is cached, using the key. If the resource is found, the system retrieves the data from the cache. If the resource is not in the cache, the system retrieves it from the server and stores it in the cache for future use.

Caching can be controlled and configured in various ways, such as setting the expiration time of cached data, selectively caching certain resources, and clearing the cache when necessary to ensure that users are delivered the most recent data.


// Example of caching with JavaScript
const cache = {};

function getData(key) {
  if (cache[key]) {
    return cache[key];
  } else {
    const data = fetchDataFromServer(key);
    cache[key] = data;
    return data;
  }
}


Understanding Preemptive and Cooperative Multitasking in Operating Systems

Preemptive multitasking is a mechanism that allows the operating system to forcibly switch between different processes or tasks at pre-defined intervals or priority levels. In this method, each process is assigned a time slice, and the operating system can interrupt a running process and switch to another process, regardless of whether the current process has completed its execution or not.

On the other hand, cooperative multitasking is a method in which a running process voluntarily relinquishes control of the CPU and allows another process to execute. In this method, each process is responsible for yielding the CPU when it completes its task or enters a wait-state, and it's up to the operating system to decide which process to run next.

The key difference between the two methods is that in preemptive multitasking, the operating system has full control over task switching and can ensure that no process monopolizes the CPU. Whereas, in cooperative multitasking, the responsibility of task switching lies with the individual processes, and the operating system has less control over the process execution.

In summary, preemptive multitasking provides a more robust and secure way of managing multiple processes in an operating system, whereas cooperative multitasking can be more efficient in certain situations.

What is Plumbing/Piping in Linux or Unix?

In Linux or Unix, plumbing/piping refers to the process of connecting two or more commands together so that the output of one command becomes the input of the next command. This enables users to perform complex tasks and automate processes by chaining together simple commands. The pipe symbol "|" is used to connect commands and is a fundamental concept in the Unix philosophy of designing small, simple tools that do one thing well and can be easily combined to form more complex systems.

Typical Elements of a Processed Image

There are several typical elements that can be found in a processed image, including:

- Pixels: The individual points of color that make up the image. - Resolution: The number of pixels per unit of measurement, usually expressed in pixels per inch (ppi) or dots per inch (dpi). - Color Space: The range of colors that can be displayed in the image, usually defined by a specific color model such as RGB or CMYK. - Compression: The process of reducing the file size of the image by encoding the data in a more efficient way, often at the expense of some image quality. - Image Format: The specific file format used to store the image data on disk, such as JPEG, PNG, or TIFF. - Metadata: Additional information about the image, such as the date it was created or the camera settings used to capture it.

Code:

elements = ["pixels", "resolution", "color space", "compression", "image format", "metadata"]

The "elements" list contains all the typical elements of a processed image as strings.

Explaining the Concept of Trapdoor in Operating Systems

In the context of Operating Systems (OS), a trapdoor, also known as a backdoor, is a secret entry point into a program or system that bypasses normal security mechanisms. Developers often build trapdoors into their systems for debugging and testing purposes, but cybercriminals can exploit them to gain unauthorized access to sensitive information. Trapdoors can be in the form of hidden user accounts, applications, or scripts and can be triggered by certain commands or activities.


# Sample code to illustrate a trapdoor
if (user == "admin" && password == "letmein") {
   allowAccess();
}


Translation Lookaside Buffer (TLB) Explanation

The Translation Lookaside Buffer (TLB) is a cache that stores recent translations of virtual memory to physical memory addresses. It is a memory cache that is typically located on the processor chip and provides faster access to memory locations. When a virtual memory address is being accessed, the TLB checks if the address exists in its cache and retrieves the corresponding physical memory address. If the address does not exist in the TLB, the processor has to make a page table walk to retrieve the physical memory address, which is slower. The TLB is a crucial component in the virtual memory management of modern operating systems.

What are Resident Set and Working Set?

Resident set refers to the portion of a process's memory that is currently stored in physical memory. While the working set is the set of pages of a process that are currently in physical memory and actively accessed during the execution of the process. Both of these terms are often used in memory management and play an important role in the performance of computer systems.

Differences between RSA and DSA

The major differences between RSA and DSA are:


- RSA is an encryption algorithm, while DSA is a digital signature algorithm.
- RSA uses a prime factorization problem while DSA uses discrete logarithms to provide data security.
- RSA keys can be used for encryption as well as digital signatures, while DSA keys can only be used for digital signatures.
- RSA is based on the difficulty of factoring large numbers, while DSA is based on the discrete logarithm problem in a finite field.
- RSA has been in use since the 1970s, while DSA was introduced in the 1990s.
- RSA is generally faster when used for encryption, while DSA is faster when used for digital signatures.

H3 tag: Bridge Router (Also Known as Brouther)

A bridge router, also referred to as a brouther, is a networking device that performs the functions of both a bridge and a router. It connects multiple networks and forwards data packets between them. By doing this, it extends the reach of a network and helps prevent the broadcast of unnecessary traffic. Bridge routers are often used in small to medium-sized businesses to connect different departments or to extend the coverage of a wireless network.

Overview of Exterior Gateway Protocol (EGP)

Exterior Gateway Protocol (EGP) is a protocol used by routers in a network to exchange routing information across autonomous systems (AS). It enables communication between different AS's so that packets can be sent and received between networks. EGP is an older, less sophisticated protocol compared to the more commonly used Border Gateway Protocol (BGP), which is used in modern networks.

Understanding Network Virtual Terminal (NVT)

The Network Virtual Terminal (NVT) is a protocol that defines the way data is exchanged between a remote computer and a local computer over a communication network. It is a software interface that allows a terminal-like application to communicate with a host computer using a standard network protocol such as TCP/IP.

NVT helps to standardize the way data is transmitted over different types of networks, regardless of the equipment or software used at either end. This way, different types of computers and terminals can communicate effectively without compatibility issues.

NVT is widely used in network-based communication protocols such as Telnet and SSH, which allow remote login and control of a host computer over a network. It defines a set of control and data characters that are used for various functions such as terminal identification, line speed negotiation, and control of the data stream.

In summary, NVT enables efficient and interoperable communication between different types of computers and software over a network. Its standardization makes it a crucial component of modern network communication.

Understanding the Hamming Code

The Hamming Code is an error-correcting code used in digital communication to detect and correct errors that occur during data transmission. It was first introduced by Richard Hamming in 1950 and is widely used in computer memory systems, satellite communication, and other digital communication technologies.

The code works by adding a set of redundant bits to the original data bits, which creates a larger code word. These redundant bits are calculated in such a way that they allow the receiver to detect and correct single-bit errors that occur during transmission.

The Hamming Code is designed to detect and correct up to 2-bit errors and to detect but not correct 3-bit errors. By using this code, the receiver can verify whether the received data is correct and can request the retransmission of any packets that contain uncorrectable errors.

Overall, the Hamming Code is an important tool in digital communication, as it helps ensure the accuracy and reliability of data transmission.

The Purpose of Pseudo TTY (PTY) or Pseudo Terminals

A Pseudo TTY or PTY is a pair of virtual terminals that emulates traditional serial communication interfaces. The primary purpose of PTY is to allow multiple processes to interact with each other as if they were communicating through a physical terminal. PTYs are commonly used by terminal emulators and application programs that require a terminal-like input/output interface. They are also widely used in remote access, networking and debugging applications. Essentially, PTYs provide a way to connect processes together, acting as a bridge between them.

Overview of BufferedWriter, flush(), and close()

The BufferedWriter class in Java is used to write text to character files with better performance than FileWriter. It buffers the data internally before writing it to the file, which reduces the number of I/O operations.

The flush() method is used to write any remaining data in the buffer to the file, ensuring that the contents are written immediately rather than waiting for the buffer to fill up. This is useful in situations where the file needs to be updated immediately, such as when logging real-time events.

The close() method is used to release the resources held by the Writer. This includes the flushing of any remaining data, closing the underlying stream, and releasing any system resources associated with the writer. It should always be called at the end of writing to a file to ensure that all resources are properly released.

Here's an example of using BufferedWriter to write to a file:


import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class FileWriterExample {

    public static void main(String[] args) {
        try {
            BufferedWriter writer = new BufferedWriter(new FileWriter("example.txt"));

            writer.write("Hello, world!");

            writer.flush();  // write any remaining data to the file

            writer.close();  // release resources held by the writer
        } catch (IOException e) {
            System.err.println("Error writing to file: " + e.getMessage());
        }
    }
}

In this example, BufferedWriter is used to write the text "Hello, world!" to a file named "example.txt". The buffer is flushed using the flush() method and the resources are released with close(). Any errors encountered while writing to the file are caught and printed to the console.

Explanation of Memory Structures: Stack and Heap

In computer memory, the stack and the heap are two memory structures used for storing data. The stack stores data in a LIFO (last in, first out) order and is used for storing variables and function calls in a program. The heap stores data in a more flexible and dynamic way and is used for dynamically allocated memory, such as objects in an object-oriented program.

The stack and heap are related to each other in that they are both parts of a program's memory space, and they interact with each other when functions are called and memory is allocated and deallocated. When a function is called, the function call is placed on the stack along with its local variables. When the function returns, the call is removed from the stack, and the memory used for the local variables is released.

Heap memory, on the other hand, is allocated and deallocated dynamically during runtime and is not managed by the program's stack. Memory in the heap can be allocated using functions like `malloc()` and `calloc()`, and deallocated using `free()`. The heap is used for storing data that needs to be used across multiple functions or for dynamic data that cannot be predicted at compile-time.

Proper understanding of these memory structures is crucial in writing efficient and effective computer programs.

Can an Object be "Resurrected" after Garbage Collection in Java?

No, it is not possible to resurrect an object that has already been marked for garbage collection in Java. Once an object is no longer referenced and is eligible for garbage collection, the memory occupied by that object is freed-up for reuse by the Java Virtual Machine. Once the object is collected, there is no way to access it again.

Can static methods be overridden and overloaded in Java? Can private methods be overridden in Java?

In Java, it is not possible to override a static method, but it can be overloaded with a different signature. On the other hand, private methods cannot be overridden in Java. They can only be accessed within the class they are defined in.

Understanding Monkey Patching in Python

Monkey patching in Python is the process of making dynamic modifications to a class or module at runtime by replacing its attributes or methods programmatically. This can be useful in situations where it is not feasible or practical to modify the original code directly, such as when dealing with third-party libraries or legacy code.

One common use case for monkey patching is to modify the behavior of a method or function without having to modify the original source code. This can be done by creating a new method or function with the same name as the original, and then replacing the original with the new version using the assignment operator.

While monkey patching can be a powerful tool, it should be used sparingly and with caution, as it can make code harder to reason about and debug. It is also important to note that some libraries and frameworks may not be compatible with monkey patching, so it is always a good idea to review the documentation and best practices before attempting to use this technique in your code.


# Example of monkey patching
class MyClass:
    def my_method(self, x):
        return x + 1

def new_method(self, x):
    return x + 2

# Monkey patching the MyClass
MyClass.my_method = new_method

obj = MyClass()
obj.my_method(2) # Output will be 4

The code above is an example of monkey patching in Python. We define a simple class with a method 'my_method' that adds 1 to the input argument. Next, we define a new method 'new_method' that adds 2 instead of 1. Finally, we replace the original 'my_method' with the new version using the assignment operator. When we call the method on an instance of the class, it returns the modified result, showing that the monkey patch was successful.

Addition without Arithmetic Operators


function add(num1, num2) {
    if(num2 == 0) {
        return num1;
    } else {
        return add(num1 ^ num2, (num1 & num2) << 1);
    }
}

// Example usage
console.log(add(25, 17)); // Output: 42

The add() function uses bitwise operators to simulate addition of two numbers without using arithmetic operators. It first checks if the second number is 0, in which case it returns the first number. If the second number is not 0, the function recursively calls itself with the bitwise XOR of the two numbers and the bitwise AND of the two numbers left-shifted by 1 position. The recursion continues until the second number becomes 0, and the result is returned.

C++ Code to print numbers from 0 to 100 without using loop and recursion


#include<iostream>
using namespace std;

int main() {
    int n = 0;
    start: //using goto statement
    cout << n << " ";
    n++;
    if (n <= 100) goto start;
    return 0;
}

This code uses a goto statement to jump back to the start label and print the next number until 100 is reached. Although, the use of goto statement is not considered good programming practice as it often leads to code that is hard to read or debug. In general, it is recommended to use loops and recursion for tasks like this instead of goto statements.

Cognizant Interview Preparation

Below are some tips to help you prepare for your Cognizant interview:

  • Research the company and the role you are applying for.
  • Practice common interview questions and prepare responses.
  • Dress professionally and arrive on time to the interview.
  • Bring a copy of your resume and any relevant certificates or documents.
  • Show enthusiasm and a positive attitude during the interview.
  • Ask questions about the company and the role.
  • Follow up with a thank you email or phone call after the interview.
// It is recommended to also prepare technically for the interview based on the job description.


Finding the Lowest Common Multiple (LCM)


//Function to find the LCM of two numbers
function findLCM(num1, num2) {
    var max = Math.max(num1, num2);
    var min = Math.min(num1, num2);
    var result = max;

    //Loop to find the LCM
    while (result % min !== 0) {
        result += max;
    }
    return result;
}

//Sample usage
console.log(findLCM(4, 6)); //Output: 12
console.log(findLCM(10, 15)); //Output: 30

This code shows a simple implementation of finding the lowest common multiple (LCM) of two numbers using JavaScript. The function receives two numbers and returns their LCM.

Character Frequencies

This code solves the problem of counting the frequency of each character in a given string. The input string is taken as a parameter and returns a dictionary in which the keys are characters that appear in the input string and the values are the frequency of each character in the input string.


def count_char_freq(input_string):
    """
    This function takes a string as an input and counts the frequency of each character in the input string.
    It returns a dictionary where the keys are characters that appear in the input string and the values are the frequency of each character in the input string.
    """
    char_freq_dict = {}  # initialize an empty dictionary to store character frequencies

    for char in input_string:
        if char in char_freq_dict:  # check if character already exists in the dictionary
            char_freq_dict[char] += 1
        else:
            char_freq_dict[char] = 1

    return char_freq_dict


Identifying the Season


const month = parseInt(prompt("Enter the month as a number (1-12): "));

if (month >= 3 && month <= 5) {
  console.log("Spring");
} else if (month >= 6 && month <= 8) {
  console.log("Summer");
} else if (month >= 9 && month <= 11) {
  console.log("Fall");
} else {
  console.log("Winter");
}

The above code helps in identifying the season based on the inputted month by the user. It takes input from the user in the form of the month number and then evaluates it through conditional statements to give output in the form of a season. It is a simple and efficient way to help users in determining the season based on the month.

Pangram Checker - Checking if a Sentence Contains Every Letter of the Alphabet

This program checks if a given sentence is a pangram, meaning it contains every letter of the alphabet at least once. It uses a set data structure to keep track of the letters in the sentence. The time complexity of this solution is O(n), where n is the length of the sentence.

Code:


def is_pangram(sentence):
    # Convert sentence to lowercase to ignore case
    sentence = sentence.lower()
    # Create an empty set to keep track of letters
    letters = set()
    # Iterate over each character in the sentence
    for char in sentence:
        # Check if character is an alphabetical letter
        if char.isalpha():
            # Add letter to the set
            letters.add(char)
    # If the set contains all letters of the alphabet, return True
    return len(letters) == 26

We can test the function with the following code:


print(is_pangram('The quick brown fox jumps over the lazy dog'))
# Output: True

print(is_pangram('The quick brown fox jumps over the lazy cat'))
# Output: False

This program can be used as a utility function in other programs that require pangram checking, such as word games or data analysis.

View Cognizant Interview Questions


    /coding-interview-questions/#tags[]=466

This code snippet provides a URL to view all interview questions related to Cognizant.

Frequently Asked Questions

1. Is the Cognizant interview difficult?

What is the entry-level salary at Cognizant?

Could you please provide more information about the job position you are inquiring about at Cognizant? Salaries vary depending on the specific role, location, and level of experience.

What Kind of Questions are Asked in a Cognizant Job Interview?

In a Cognizant job interview, the questions can vary depending on the position being applied for. However, there are some common questions that are asked across most roles. These include:

1. Can you tell us a little about yourself? 2. What are your strengths and weaknesses? 3. How do you handle stressful situations at work? 4. What motivates you to work and excel in your field? 5. Can you walk us through your work experience and highlight some of your achievements? 6. How do you keep yourself updated with the latest technologies and industry trends? 7. Have you ever faced a difficult or challenging situation at work, and how did you overcome it? 8. Why do you want to work for Cognizant specifically?

It is also common for candidates to be given specific technical questions to test their knowledge and skills in their area of expertise. Candidates should come well-prepared and be ready to demonstrate their capabilities to the interviewer.

Does Cognizant have bonds for their employees?

At Cognizant, there may be a bond for employees depending on their role and the terms of their employment.

Is There a Dress Code at Cognizant?

As an AI language model, I don't have information about Cognizant's dress code policy. However, it's essential to remember that many companies implement dress codes to maintain professionalism and create a specific brand image. It's best to check with the HR department or review the employee handbook for the dress code guidelines.

How to Apply for a Job at Cognizant

If you're interested in applying for a job at Cognizant, there are several steps you can take. First, visit the Cognizant careers website to search for open positions that fit your skills and experience. Once you find a position you're interested in, review the job description and requirements to ensure that you're a good fit for the role. Then, prepare your resume and cover letter to showcase your qualifications and experience.

Finally, submit your application through the Cognizant careers website or by following the instructions in the job posting. It's important to tailor your application to the specific role you're applying for and to highlight your skills and experience that are most relevant to the position. Good luck with your job search!

How Many Rounds are there in a Cognizant Interview?

As an AI language model, I don't have the updated information on the current hiring process of Cognizant. However, based on some online sources and past experiences, typically the interview process at Cognizant consists of multiple rounds, which can vary based on the position you are applying for, the level of experience, and the location. The rounds may include a screening call, technical interviews, behavioral interviews, and a final round with the hiring manager.

It is always a good idea to research and prepare for the interview rounds beforehand, including researching the company, practicing common interview questions, and refreshing your technical knowledge, if needed.

What is the Career Growth like at Cognizant?

Cognizant offers various career growth opportunities for its employees. The company has a well-defined career path and provides training and development programs to help employees enhance their skills and meet their career goals. The company also encourages employees to take up challenging assignments and provides them with opportunities to work on different projects.

Additionally, Cognizant offers a performance-based culture where employees can advance based on their performance and contribution to the company. The company also has a comprehensive performance management process that provides employees with continuous feedback and coaching to improve their performance.

Technical Interview Guides

Here are guides for technical interviews, categorized from introductory to advanced levels.

View All

Best MCQ

As part of their written examination, numerous tech companies necessitate candidates to complete multiple-choice questions (MCQs) assessing their technical aptitude.

View MCQ's
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.