1596429120

# What is a Palindrome?

A palindrome is a word that reads the same forwards and backwards. In my universe, there are two kinds of palindrome: “Odd Pal” and “Even Pal”.

## Even Pal

Even Pal is a palindrome which has an even length, for example: “ZYXXYZ”. In the visualization below you can see how we can split it into 2 parts that have size 3: “ZYX” and “XYZ” . This palindrome will always have two centres called Left Center” at index2 and “Right Center” at index3.

“Even Pal”

Notice that:

• character at index2 = character at index3 (mirror 1)
• character at index1 = character at index4 (mirror 2)
• character at index0 = character at index5 (mirror 3)

It is because of the above equality of characters at their respective indexes that the string is a palindrome and the two parts look like a sequence of 3 mirrors.

## Odd Pal

Odd Pal is a palindrome which has an odd length, example: “ZYXWXYZ”. In the visualization below you can see how we can split the string into 2 parts that have size 3: “ZYX” and “XYZ”, while “W” at index3 becomes the center.

“Odd Pal”

Notice that:

• character at index2 = character at index4 (mirror 1)
• character at index1 = character at index5 (mirror 2)
• character at index0 = character at index6 (mirror 3)

Notice how again the two parts look like a sequence of 3 mirrors.

# Problem

The problem states that we have to find the longest substring that is a palindrome in the string. A substring is a section of a string that consists of contiguous elements. Some examples are:

Input1: “BABAD” | Output1: “BAB” or “ABA”

Input2: “CBBD” | Output2: “BB”

Input3: “A” | Output3: “A”

# Solutions

## O(n²) Complexity

The simplest way to solve for this is to take every index as 1) a center 2) a Left Center and expand outwards to make character comparisons and find mirrors. The sequence with the maximum number of mirrors would be returned. Seems very simple and intuitive but the complexity is O(n²) because expanding a palindrome around a center could take O(n) time and we will explore every index in the string to be a center and left center, so O(n²) would be the time complexity.

## O(n) Complexity

We can improve this runtime if we think of a way where we can leverage the previous palindromes found (as we navigate through the string) and reduce the “expanding outwards” part. Luckily, this is possible with “Manachar’s algorithm”.

# Manachar’s algorithm

Before diving into the algorithm itself, we need to learn a few things first. For simplicity we will be focusing on Odd Pals for the most part. So let’s learn a few things in order:

#palindrome #leetcode #algorithms #substring #coding #algorithms

1596429120

# What is a Palindrome?

A palindrome is a word that reads the same forwards and backwards. In my universe, there are two kinds of palindrome: “Odd Pal” and “Even Pal”.

## Even Pal

Even Pal is a palindrome which has an even length, for example: “ZYXXYZ”. In the visualization below you can see how we can split it into 2 parts that have size 3: “ZYX” and “XYZ” . This palindrome will always have two centres called Left Center” at index2 and “Right Center” at index3.

“Even Pal”

Notice that:

• character at index2 = character at index3 (mirror 1)
• character at index1 = character at index4 (mirror 2)
• character at index0 = character at index5 (mirror 3)

It is because of the above equality of characters at their respective indexes that the string is a palindrome and the two parts look like a sequence of 3 mirrors.

## Odd Pal

Odd Pal is a palindrome which has an odd length, example: “ZYXWXYZ”. In the visualization below you can see how we can split the string into 2 parts that have size 3: “ZYX” and “XYZ”, while “W” at index3 becomes the center.

“Odd Pal”

Notice that:

• character at index2 = character at index4 (mirror 1)
• character at index1 = character at index5 (mirror 2)
• character at index0 = character at index6 (mirror 3)

Notice how again the two parts look like a sequence of 3 mirrors.

# Problem

The problem states that we have to find the longest substring that is a palindrome in the string. A substring is a section of a string that consists of contiguous elements. Some examples are:

Input1: “BABAD” | Output1: “BAB” or “ABA”

Input2: “CBBD” | Output2: “BB”

Input3: “A” | Output3: “A”

# Solutions

## O(n²) Complexity

The simplest way to solve for this is to take every index as 1) a center 2) a Left Center and expand outwards to make character comparisons and find mirrors. The sequence with the maximum number of mirrors would be returned. Seems very simple and intuitive but the complexity is O(n²) because expanding a palindrome around a center could take O(n) time and we will explore every index in the string to be a center and left center, so O(n²) would be the time complexity.

## O(n) Complexity

We can improve this runtime if we think of a way where we can leverage the previous palindromes found (as we navigate through the string) and reduce the “expanding outwards” part. Luckily, this is possible with “Manachar’s algorithm”.

# Manachar’s algorithm

Before diving into the algorithm itself, we need to learn a few things first. For simplicity we will be focusing on Odd Pals for the most part. So let’s learn a few things in order:

#palindrome #leetcode #algorithms #substring #coding #algorithms

1656151740

## Test_cov_console: Flutter Console Coverage Test

Flutter Console Coverage Test

This small dart tools is used to generate Flutter Coverage Test report to console

## How to install

Add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

``````dev_dependencies:
test_cov_console: ^0.2.2
``````

## How to run

### run the following command to make sure all flutter library is up-to-date

``````flutter pub get
Running "flutter pub get" in coverage...                            0.5s
``````

### run the following command to generate lcov.info on coverage directory

``````flutter test --coverage
00:02 +1: All tests passed!
``````

### run the tool to generate report from lcov.info

``````flutter pub run test_cov_console
---------------------------------------------|---------|---------|---------|-------------------|
File                                         |% Branch | % Funcs | % Lines | Uncovered Line #s |
---------------------------------------------|---------|---------|---------|-------------------|
lib/src/                                     |         |         |         |                   |
print_cov.dart                              |  100.00 |  100.00 |   88.37 |...,149,205,206,207|
print_cov_constants.dart                    |    0.00 |    0.00 |    0.00 |    no unit testing|
lib/                                         |         |         |         |                   |
test_cov_console.dart                       |    0.00 |    0.00 |    0.00 |    no unit testing|
---------------------------------------------|---------|---------|---------|-------------------|
All files with unit testing                 |  100.00 |  100.00 |   88.37 |                   |
---------------------------------------------|---------|---------|---------|-------------------|
``````

## Optional parameter

``````If not given a FILE, "coverage/lcov.info" will be used.
-f, --file=<FILE>                      The target lcov.info file to be reported
-e, --exclude=<STRING1,STRING2,...>    A list of contains string for files without unit testing
to be excluded from report
-l, --line                             It will print Lines & Uncovered Lines only
Branch & Functions coverage percentage will not be printed
-i, --ignore                           It will not print any file without unit testing
-m, --multi                            Report from multiple lcov.info files
-c, --csv                              Output to CSV file
-o, --output=<CSV-FILE>                Full path of output CSV file
If not given, "coverage/test_cov_console.csv" will be used
-t, --total                            Print only the total coverage
Note: it will ignore all other option (if any), except -m
-p, --pass=<MINIMUM>                   Print only the whether total coverage is passed MINIMUM value or not
If the value >= MINIMUM, it will print PASSED, otherwise FAILED
Note: it will ignore all other option (if any), except -m
-h, --help                             Show this help
``````

### example run the tool with parameters

``````flutter pub run test_cov_console --file=coverage/lcov.info --exclude=_constants,_mock
---------------------------------------------|---------|---------|---------|-------------------|
File                                         |% Branch | % Funcs | % Lines | Uncovered Line #s |
---------------------------------------------|---------|---------|---------|-------------------|
lib/src/                                     |         |         |         |                   |
print_cov.dart                              |  100.00 |  100.00 |   88.37 |...,149,205,206,207|
lib/                                         |         |         |         |                   |
test_cov_console.dart                       |    0.00 |    0.00 |    0.00 |    no unit testing|
---------------------------------------------|---------|---------|---------|-------------------|
All files with unit testing                 |  100.00 |  100.00 |   88.37 |                   |
---------------------------------------------|---------|---------|---------|-------------------|
``````

### report for multiple lcov.info files (-m, --multi)

``````It support to run for multiple lcov.info files with the followings directory structures:
1. No root module
<root>/<module_a>
<root>/<module_a>/coverage/lcov.info
<root>/<module_a>/lib/src
<root>/<module_b>
<root>/<module_b>/coverage/lcov.info
<root>/<module_b>/lib/src
...
2. With root module
<root>/coverage/lcov.info
<root>/lib/src
<root>/<module_a>
<root>/<module_a>/coverage/lcov.info
<root>/<module_a>/lib/src
<root>/<module_b>
<root>/<module_b>/coverage/lcov.info
<root>/<module_b>/lib/src
...
You must run test_cov_console on <root> dir, and the report would be grouped by module, here is
the sample output for directory structure 'with root module':
flutter pub run test_cov_console --file=coverage/lcov.info --exclude=_constants,_mock --multi
---------------------------------------------|---------|---------|---------|-------------------|
File                                         |% Branch | % Funcs | % Lines | Uncovered Line #s |
---------------------------------------------|---------|---------|---------|-------------------|
lib/src/                                     |         |         |         |                   |
print_cov.dart                              |  100.00 |  100.00 |   88.37 |...,149,205,206,207|
lib/                                         |         |         |         |                   |
test_cov_console.dart                       |    0.00 |    0.00 |    0.00 |    no unit testing|
---------------------------------------------|---------|---------|---------|-------------------|
All files with unit testing                 |  100.00 |  100.00 |   88.37 |                   |
---------------------------------------------|---------|---------|---------|-------------------|
---------------------------------------------|---------|---------|---------|-------------------|
File - module_a -                            |% Branch | % Funcs | % Lines | Uncovered Line #s |
---------------------------------------------|---------|---------|---------|-------------------|
lib/src/                                     |         |         |         |                   |
print_cov.dart                              |  100.00 |  100.00 |   88.37 |...,149,205,206,207|
lib/                                         |         |         |         |                   |
test_cov_console.dart                       |    0.00 |    0.00 |    0.00 |    no unit testing|
---------------------------------------------|---------|---------|---------|-------------------|
All files with unit testing                 |  100.00 |  100.00 |   88.37 |                   |
---------------------------------------------|---------|---------|---------|-------------------|
---------------------------------------------|---------|---------|---------|-------------------|
File - module_b -                            |% Branch | % Funcs | % Lines | Uncovered Line #s |
---------------------------------------------|---------|---------|---------|-------------------|
lib/src/                                     |         |         |         |                   |
print_cov.dart                              |  100.00 |  100.00 |   88.37 |...,149,205,206,207|
lib/                                         |         |         |         |                   |
test_cov_console.dart                       |    0.00 |    0.00 |    0.00 |    no unit testing|
---------------------------------------------|---------|---------|---------|-------------------|
All files with unit testing                 |  100.00 |  100.00 |   88.37 |                   |
---------------------------------------------|---------|---------|---------|-------------------|
``````

### Output to CSV file (-c, --csv, -o, --output)

``````flutter pub run test_cov_console -c --output=coverage/test_coverage.csv

#### sample CSV output file:
File,% Branch,% Funcs,% Lines,Uncovered Line #s
lib/,,,,
test_cov_console.dart,0.00,0.00,0.00,no unit testing
lib/src/,,,,
parser.dart,100.00,100.00,97.22,"97"
parser_constants.dart,100.00,100.00,100.00,""
print_cov.dart,100.00,100.00,82.91,"29,49,51,52,171,174,177,180,183,184,185,186,187,188,279,324,325,387,388,389,390,391,392,393,394,395,398"
print_cov_constants.dart,0.00,0.00,0.00,no unit testing
All files with unit testing,100.00,100.00,86.07,""``````

## Use this package as an executable

### Install it

You can install the package from the command line:

``dart pub global activate test_cov_console``

### Use it

The package has the following executables:

``````\$ test_cov_console
``````

## Use this package as a library

### Depend on it

Run this command:

With Dart:

`` \$ dart pub add test_cov_console``

With Flutter:

`` \$ flutter pub add test_cov_console``

This will add a line like this to your package's pubspec.yaml (and run an implicit `dart pub get`):

``````dependencies:
test_cov_console: ^0.2.2``````

Alternatively, your editor might support `dart pub get` or `flutter pub get`. Check the docs for your editor to learn more.

### Import it

Now in your Dart code, you can use:

``import 'package:test_cov_console/test_cov_console.dart';``

example/lib/main.dart

``````import 'package:flutter/material.dart';

void main() {
runApp(MyApp());
}

class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
// This makes the visual density adapt to the platform that you run
// the app on. For desktop platforms, the controls will be smaller and
// closer together (more dense) than on mobile platforms.
),
);
}
}

class MyHomePage extends StatefulWidget {
MyHomePage({Key? key, required this.title}) : super(key: key);

// that it has a State object (defined below) that contains fields that affect
// how it looks.

// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".

final String title;

@override
_MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;

void _incrementCounter() {
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
});
}

@override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
// Column is also a layout widget. It takes a list of children and
// arranges them vertically. By default, it sizes itself to fit its
// children horizontally, and tries to be as tall as its parent.
//
// Invoke "debug painting" (press "p" in the console, choose the
// "Toggle Debug Paint" action from the Flutter Inspector in Android
// Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
// to see the wireframe for each widget.
//
// Column has various properties to control how it sizes itself and
// how it positions its children. Here we use mainAxisAlignment to
// center the children vertically; the main axis here is the vertical
// axis because Columns are vertical (the cross axis would be
// horizontal).
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'\$_counter',
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}``````

Author: DigitalKatalis
Source Code: https://github.com/DigitalKatalis/test_cov_console

1624874940

## Leetcodes Algorithm Series: Contains Duplicate

Hello, hello! As I continue my job search, I am practicing my algorithm questions on Leetcode. So, I thought I would blog about some Leetcode problems as I solve them.

As a Bootcamp graduate, I did not get much practice in algorithms, so it has been a very fun and sometimes frustrating trial and error in recognizing patterns, optimizing my code to be faster (looking at you Big-O), learning how to break down a problem, and sometimes implementing neat math tricks to solve these algorithm problems. I have been practicing them using JavaScript.

As I’m relatively new to algorithm problems, I’ve started out with their Easy Collection of Top Interview Questions. So in Contains Duplicate:

Given an integer array `nums`, return `true` if any value appears at least twice in the array, and return `false` if every element is distinct.

Examples:

``````Input: nums = [1,2,3,1]
Output: true

Input: nums = [1,2,3,4]
Output: false
Input: nums = [1,1,1,3,3,4,3,2,4,2]
Output: true
``````

Simply, if any numbers in the array appear more than once in the array, I need to return `true` . Now, I will definitely need to figure out a way to compare a number to the other numbers. Additionally, I will most likely need to loop through the array so I have access to each number to then compare it to others.

First, I thought that I could iterate through the array, and at each instance, I iterate through another loop of the remaining integers and compare them to see if any are equal (===). However, per my beginner understanding of Big-O, this would yield me an unfavorable time complexity of O(n²).

Then, I thought that I could create an object and count how many times a number in the array appears. By doing this, I could then check to see if any of the numbers had a count greater than 1. If so, then I could return `true` else I would return `false` .

#computer-science #leetcode #javascript #programming #algorithms #leetcodes algorithm

1597507280

## Longest substring whose characters can be rearranged to form a Palindrome

A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.

#bit magic #mathematical #strings #palindrome #substring #algorithms

1594945380

# Problem

Given a string, find the length of the longest sub-string without repeating characters.

# Examples

## Example 1

``````Input: "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
``````

## Example 2

``````Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
``````

## Example 3

``````Input: "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3\. Note that the answer must be a sub-string, "pwke" is a sub-sequence and not a sub-string.
``````

# A note on Strings in Rust

One thing to note is that Rust does not implement traditional string indexing due to issues that come up with utf-8 encodings. There are a few approaches to get characters out of a string, but I’ll just convert the input string to a vector of chars. It’s an interesting topic, but out of scope for this article.

# Approach 1: Brute Force

A naive solution to this problem is to iterate through every possible sub-string and track the length of the longest sub-string seen so far.

# Algorithm

This approach can be separated into two function. One function should handle iterating over the sub-strings and tracking the length of the longest sub-string. The other function should handle check for uniqueness.

## Sub-string Iteration Algorithm

To iterate over the sub-strings, this approach uses two loops. The outer loop iterates from `i` to `n` where `n` is the length of the input string. The inner loop iterates from `i` + 1 to `n` inclusively.

The algorithm looks like this:

``````initialize n to length of string
initialize length to 0
for i = 0 to n
for j = i + 1 to n + 1
if sub-string of characters between i and j are unique
update length if j - i is greater than current length
return length
``````

## All Unique Algorithm

To check if a sub-strings characters are all unique, this function will add each character to a set. If a duplicate character is found the function will return false, otherwise it will return true.

This algorithm looks like this:

``````initialize a HashSet of char
initialize a vector of chars
for i = start to end
if the char exists in the set
return false
else